UNPKG

authservice-nextjs

Version:

Next.js SDK for Auth Service - Server and client-side authentication with App Router support

35 lines 1.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createAuthMiddleware = createAuthMiddleware; exports.authMiddlewareConfig = authMiddlewareConfig; const server_1 = require("next/server"); function createAuthMiddleware(config) { return async function middleware(request) { const token = request.cookies.get(config.cookieName || 'auth-token'); const protectedPaths = ['/dashboard', '/admin', '/profile']; const authPaths = ['/login', '/signup']; const path = request.nextUrl.pathname; const isProtectedPath = protectedPaths.some((p) => path.startsWith(p)); const isAuthPath = authPaths.some((p) => path.startsWith(p)); if (isProtectedPath && !token) { const loginUrl = new URL(config.loginUrl || '/login', request.url); loginUrl.searchParams.set('returnUrl', request.nextUrl.pathname); return server_1.NextResponse.redirect(loginUrl); } if (isAuthPath && token) { return server_1.NextResponse.redirect(new URL('/dashboard', request.url)); } return server_1.NextResponse.next(); }; } function authMiddlewareConfig(customPaths) { const defaultProtected = ['/dashboard', '/admin', '/profile', '/settings']; const defaultPublic = ['/login', '/signup', '/forgot-password']; return { matcher: [ ...(customPaths?.protected || defaultProtected).map((p) => `${p}/:path*`), ...(customPaths?.public || defaultPublic).map((p) => `${p}/:path*`), ], }; } //# sourceMappingURL=middleware.js.map