ef3481744c
- src/middleware.ts: Edge-compatible token validation via fetch() (no Drizzle import) - src/app/api/internal/validate-token/route.ts: Node.js route queries clients.token via Drizzle - Invalid tokens rewrite to /not-found (404); matcher scoped to /c/:path*
35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const pathname = request.nextUrl.pathname;
|
|
|
|
// Extract token from path: /c/[token]/...
|
|
const tokenMatch = pathname.match(/^\/c\/([a-zA-Z0-9_-]+)/);
|
|
if (!tokenMatch) {
|
|
return NextResponse.rewrite(new URL('/not-found', request.url));
|
|
}
|
|
|
|
const token = tokenMatch[1];
|
|
|
|
try {
|
|
// Call internal Node.js API route — Edge middleware cannot use postgres-js directly
|
|
// postgres-js requires Node.js net/tls which are unavailable in the Edge runtime
|
|
const validateUrl = new URL(
|
|
`/api/internal/validate-token?token=${encodeURIComponent(token)}`,
|
|
request.url
|
|
);
|
|
const res = await fetch(validateUrl.toString());
|
|
|
|
if (!res.ok) {
|
|
return NextResponse.rewrite(new URL('/not-found', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
} catch {
|
|
return NextResponse.rewrite(new URL('/not-found', request.url));
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/c/:path*'],
|
|
}; |