/** * @module middleware * @description hooks-up `next-auth` into the page processing pipeline */ import { auth, authConfig } from '@/app/lib/auth' import createIntlMiddleware from 'next-intl/middleware'; import { NextRequest, NextResponse } from 'next/server'; import { locales, defaultLocale } from '@/app/i18n'; const publicPages = ['/terms', '/policy', '/login']; const intlMiddleware = createIntlMiddleware({ locales, localePrefix: 'as-needed', defaultLocale }); export default async function middleware(req: NextRequest) { const publicPathnameRegex = RegExp( `^(/(${locales.join('|')}))?(${publicPages .flatMap((p) => (p === '/' ? ['', '/'] : p)) .join('|')})/?$`, 'i' ); const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname); // for punlic pages we call only localisation middleware if (!isPublicPage) { const session = await auth(); if (!session) { const signInUrl = `${req.nextUrl.protocol}//${req.nextUrl.hostname}${req.nextUrl.port ? `:${req.nextUrl.port}` : ''}${authConfig.pages?.signIn as string}`; return NextResponse.redirect( signInUrl ); } } return intlMiddleware(req); } export const config = { // for these paths middleware will not be called matcher: [ '/((?!api|_next/static|_next/image|.*\\.png$|.*\\.webm$).*)', ], };