forked from builders-garden/miniapp-next-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
48 lines (41 loc) · 1.27 KB
/
middleware.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
import { NextRequest, NextResponse } from "next/server";
import * as jose from "jose";
import { env } from "./lib/env";
export const config = {
matcher: ["/api/:path*"],
};
export default async function middleware(req: NextRequest) {
// Skip auth check for sign-in endpoint
if (
req.nextUrl.pathname === "/api/auth/sign-in" ||
req.nextUrl.pathname.includes("/api/og") ||
req.nextUrl.pathname.includes("/api/webhook")
) {
return NextResponse.next();
}
// Get token from auth_token cookie
const token = req.cookies.get("auth_token")?.value;
if (!token) {
return NextResponse.json(
{ error: "Authentication required" },
{ status: 401 }
);
}
try {
const secret = new TextEncoder().encode(env.JWT_SECRET);
// Verify the token using jose
const { payload } = await jose.jwtVerify(token, secret);
// Clone the request headers to add user info
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-user-fid", payload.fid as string);
// Return response with modified headers
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
} catch (error) {
console.error(error);
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
}
}