53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import authConfig from "@/auth.config"
|
|
import NextAuth from "next-auth"
|
|
|
|
import {
|
|
DEFAULT_REDIRECT,
|
|
PUBLIC_ROUTES,
|
|
AUTH_ROUTES,
|
|
API_PREFIX
|
|
} from "@/routes"
|
|
import { NextResponse } from "next/server"
|
|
|
|
const { auth } = NextAuth(authConfig)
|
|
|
|
export default auth((req) => {
|
|
const isLoggedIn = !!req.auth
|
|
|
|
const { nextUrl } = req
|
|
|
|
// Store current request url in a custom header, which you can read later
|
|
const requestHeaders = new Headers(req.headers);
|
|
requestHeaders.set('x-url', req.url);
|
|
|
|
const isApiRoute = nextUrl.pathname.startsWith(API_PREFIX)
|
|
const isPublicRoute = PUBLIC_ROUTES.includes(nextUrl.pathname) || nextUrl.pathname.startsWith("/overlay")
|
|
const isAuthRoute = AUTH_ROUTES.includes(nextUrl.pathname)
|
|
const response = NextResponse.next({
|
|
request: {
|
|
headers: requestHeaders,
|
|
}
|
|
});
|
|
|
|
if (isApiRoute) {
|
|
return response
|
|
}
|
|
|
|
if (isAuthRoute) {
|
|
if (isLoggedIn) {
|
|
return Response.redirect(new URL(DEFAULT_REDIRECT, nextUrl))
|
|
}
|
|
return response;
|
|
}
|
|
|
|
if (!isLoggedIn && !isPublicRoute) {
|
|
return Response.redirect(new URL("/auth/login", nextUrl))
|
|
}
|
|
|
|
return response;
|
|
})
|
|
|
|
export const config = {
|
|
// Any subpath matching this causes this middleware to be invoked.
|
|
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
|
|
} |