hermes-web/middleware.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-01-02 02:26:20 -05:00
import authConfig from "@/auth.config"
import NextAuth from "next-auth"
2023-12-30 05:56:40 -05:00
2024-01-02 02:26:20 -05:00
import {
DEFAULT_REDIRECT,
PUBLIC_ROUTES,
AUTH_ROUTES,
API_PREFIX
} from "@/routes"
import { NextResponse } from "next/server"
2023-12-30 05:56:40 -05:00
2024-01-02 02:26:20 -05:00
const { auth } = NextAuth(authConfig)
2023-12-30 05:56:40 -05:00
2024-01-02 02:26:20 -05:00
export default auth((req) => {
const isLoggedIn = !!req.auth
2023-12-30 05:56:40 -05:00
2024-01-02 02:26:20 -05:00
const { nextUrl } = req
2023-12-30 05:56:40 -05:00
// 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);
2024-01-02 02:26:20 -05:00
const isApiRoute = nextUrl.pathname.startsWith(API_PREFIX)
const isPublicRoute = PUBLIC_ROUTES.includes(nextUrl.pathname) || nextUrl.pathname.startsWith("/overlay")
2024-01-02 02:26:20 -05:00
const isAuthRoute = AUTH_ROUTES.includes(nextUrl.pathname)
const response = NextResponse.next({
request: {
headers: requestHeaders,
}
});
2024-01-02 02:26:20 -05:00
if (isApiRoute) {
return response
2024-01-02 02:26:20 -05:00
}
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(new URL(DEFAULT_REDIRECT, nextUrl))
}
return response;
2023-12-30 05:56:40 -05:00
}
2024-01-02 02:26:20 -05:00
if (!isLoggedIn && !isPublicRoute) {
return Response.redirect(new URL("/auth/login", nextUrl))
}
return response;
2024-01-02 02:26:20 -05:00
})
export const config = {
// Any subpath matching this causes this middleware to be invoked.
2024-01-02 02:26:20 -05:00
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}