yo-next-auth/middleware.ts

66 lines
2.2 KiB
TypeScript

import { NextURL } from 'next/dist/server/web/next-url'
import NextAuth from 'next-auth'
import { NextRequest, NextResponse } from 'next/server'
import { defaultLocale, locales } from '@/config/locales'
import authConfig from '@/auth.config'
import { apiAuthPrefix, AUTH_LOGIN_URL, authRoutesRegEx, DEFAULT_LOGIN_REDIRECT, publicRoutes } from '@/config/routes'
import { testPathnameRegex } from '@/lib/utils'
import { createI18nMiddleware } from 'next-international/middleware'
interface AppRouteHandlerFnContext {
params?: Record<string, string | string[]>;
}
export const middleware = (request: NextRequest, event: AppRouteHandlerFnContext): NextResponse | null => {
return NextAuth(authConfig).auth((request): any => {
const { nextUrl }: { nextUrl: NextURL } = request
const isLoggedIn: boolean = !!request.auth
const isApiAuthRoute: boolean = nextUrl.pathname.startsWith(apiAuthPrefix)
const isPublicRoute: boolean = testPathnameRegex(publicRoutes, nextUrl.pathname)
const isAuthRoute: boolean = testPathnameRegex(authRoutesRegEx, nextUrl.pathname)
if (isApiAuthRoute) {
return null
}
const I18nMiddleware = createI18nMiddleware({
locales, defaultLocale, urlMappingStrategy: 'rewriteDefault',
})
if (isAuthRoute) {
if (isLoggedIn) {
return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
}
return I18nMiddleware(request)
}
if (!isLoggedIn && !isPublicRoute) {
return NextResponse.redirect(new URL(AUTH_LOGIN_URL, nextUrl))
}
return I18nMiddleware(request)
})(request, event) as NextResponse
}
// export const config = {
// matcher: [
// /*
// * Match all request paths except for the ones starting with:
// * - api (API routes)
// * - _next/static (static files)
// * - _next/image (image optimization files)
// * - favicon.ico (favicon file)
// */
// {
// source: '/((?!.+\\.[\\w]+$|api|_next/image|favicon.ico|robots.txt|trpc).*)', missing: [
// { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }],
// }],
// }
export const config = {
matcher: [
'/((?!.+\\.[\\w]+$|_next|_next/image|_next/static).*)', '/(api|trpc)(.*)',
],
}