Skip to main content

Middleware Configuration

Learn how to configure middleware for request processing in FSS.

Next.js Middleware

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
// Check for authentication
const token = request.cookies.get('auth-token')?.value;

if (!token && !isPublicPath(request.nextUrl.pathname)) {
return NextResponse.redirect(new URL('/login', request.url));
}

return NextResponse.next();
}

function isPublicPath(pathname: string): boolean {
const publicPaths = ['/login', '/register', '/forgot-password'];
return publicPaths.some(path => pathname.startsWith(path));
}

export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

NestJS Middleware

// src/middleware/auth.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
const token = req.headers.authorization?.split(' ')[1];

if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}

// Validate token
// ...

next();
}
}