diff --git a/src/middleware.ts b/src/middleware.ts index 8e59b38..a1dc93e 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -13,7 +13,8 @@ export default authMiddleware({ '/api/files/upload', '/api/msg/new', 'api/msg/destroy', - '/api/msg/message-viewed' + '/api/msg/message-viewed', + 'api/ip' ] }) diff --git a/src/pages/api/ip.ts b/src/pages/api/ip.ts new file mode 100644 index 0000000..1e737d5 --- /dev/null +++ b/src/pages/api/ip.ts @@ -0,0 +1,22 @@ +import { NextApiRequest, NextApiResponse } from "next"; +import { IpAddressInfo } from "../../shared/types"; + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + if (req.method !== 'GET') { + res.setHeader('Allow', ['GET']) + res.status(405).json({ + error: { message: `Method ${req.method} Not Allowed` } + }) + } + + const response = await fetch('http://ip-api.com/json/') + const data = await response.json() + const { status, query, ...rest } = data + + if (status !== 'success') { + res.status(500).json({ error: 'Failed to get IP address info' }) + } + const ipInfo = { ...rest, ipAddress: query } as IpAddressInfo + + res.status(200).json({ ...ipInfo }) +} \ No newline at end of file diff --git a/src/pages/messages/[publicId].tsx b/src/pages/messages/[publicId].tsx index 4806793..eabcb44 100644 --- a/src/pages/messages/[publicId].tsx +++ b/src/pages/messages/[publicId].tsx @@ -50,9 +50,6 @@ export const getServerSideProps: GetServerSideProps = async ({ params, req }) => } }) - const ipAddressInfo = await getIpAddressInfo() - console.log(ipAddressInfo) - // log message_viewed const session = getAuth(req) const messageViewedEvent = { diff --git a/src/shared/utils.ts b/src/shared/utils.ts index b36e7eb..e30b148 100644 --- a/src/shared/utils.ts +++ b/src/shared/utils.ts @@ -176,12 +176,11 @@ export function getLiveKitURL(region?: string | string[]): string { // add return type export async function getIpAddressInfo(): Promise { - const response = await fetch('http://ip-api.com/json/') - const data = await response.json() - const { status, query, ...rest } = data - - if (status !== 'success') { - throw new Error('Failed to get IP address info') + try { + const response = await fetch('/api/ip') + return await response.json() as IpAddressInfo + } catch (error) { + console.log(error) + throw new Error('Failed to get IP address info') } - return { ...rest, ipAddress: query } as IpAddressInfo }