chatbot-template/middleware.ts

60 lines
1.5 KiB
TypeScript
Raw Normal View History

import { type NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { guestRegex, isDevelopmentEnvironment } from "./lib/constants";
2024-03-14 20:00:52 +03:00
2025-04-25 23:40:15 -07:00
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
2024-10-11 18:00:22 +05:30
2025-04-25 23:40:15 -07:00
/*
* Playwright starts the dev server and requires a 200 status to
* begin the tests, so this ensures that the tests can start
*/
if (pathname.startsWith("/ping")) {
return new Response("pong", { status: 200 });
2025-04-25 23:40:15 -07:00
}
if (pathname.startsWith("/api/auth")) {
2025-04-25 23:40:15 -07:00
return NextResponse.next();
}
const token = await getToken({
req: request,
secret: process.env.AUTH_SECRET,
secureCookie: !isDevelopmentEnvironment,
});
if (!token) {
const redirectUrl = encodeURIComponent(request.url);
return NextResponse.redirect(
new URL(`/api/auth/guest?redirectUrl=${redirectUrl}`, request.url)
2025-04-25 23:40:15 -07:00
);
}
const isGuest = guestRegex.test(token?.email ?? "");
2025-04-25 23:40:15 -07:00
if (token && !isGuest && ["/login", "/register"].includes(pathname)) {
return NextResponse.redirect(new URL("/", request.url));
2025-04-25 23:40:15 -07:00
}
return NextResponse.next();
}
2023-06-22 10:37:35 -07:00
export const config = {
2025-04-25 23:40:15 -07:00
matcher: [
"/",
"/chat/:id",
"/api/:path*",
"/login",
"/register",
2025-04-25 23:40:15 -07:00
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
2025-04-25 23:40:15 -07:00
],
2024-10-11 18:00:22 +05:30
};