/
route.ts
52 lines (47 loc) · 1.39 KB
/
route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { ratelimit } from "@/lib/upstash";
import { getUrlQuerySchema } from "@/lib/zod/schemas";
import { ipAddress } from "@vercel/edge";
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
import { getMetaTags } from "./utils";
export const runtime = "edge";
export async function GET(req: NextRequest) {
try {
const { url } = getUrlQuerySchema.parse({
url: req.nextUrl.searchParams.get("url"),
});
// Rate limit if user is not logged in
const session = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
if (!session?.email) {
const ip = ipAddress(req);
const { success } = await ratelimit().limit(`metatags:${ip}`);
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Don't DDoS me pls 🥺",
});
}
}
const metatags = await getMetaTags(url);
return NextResponse.json(metatags, {
headers: {
"Access-Control-Allow-Origin": "*",
},
});
} catch (error) {
return handleAndReturnErrorResponse(error);
}
}
export function OPTIONS() {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
},
});
}