Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { NextRequest, NextResponse } from 'next/server';
- import jwt from 'jsonwebtoken';
- // Replace with a mechanism to securely load your JWT secret
- // (e.g., environment variables, dedicated secrets management)
- const JWT_SECRET = process.env.JWT_SECRET!;
- if (!JWT_SECRET) {
- throw new Error('Missing JWT_SECRET environment variable');
- }
- export function middleware(req: NextRequest) {
- const { pathname } = req.nextUrl;
- console.log('Checking token for:', pathname); // Log the requested path
- // Exclude specific paths from token check (e.g., login, signup, public assets)
- const excludedPaths = ['/login', '/signup', '/public/'];
- if (excludedPaths.includes(pathname)) {
- return NextResponse.next();
- }
- const cookies = req.cookies;
- const token = cookies.get('token')?.value; // Extract the value from RequestCookie
- console.log('Found token:', !!token); // Log if a token is found
- // Validate token if it exists
- if (token) {
- try {
- const decoded = jwt.verify(token, JWT_SECRET);
- // Handle potentially missing username property:
- if (typeof decoded === 'string') {
- console.error('Invalid token structure: Missing username');
- return NextResponse.redirect(new URL('/signup', req.url)); // Redirect on invalid structure
- }
- console.log('Valid token for:', decoded.username || 'Unknown username'); // Log username or 'Unknown username'
- return NextResponse.next(); // Allow access if valid token
- } catch (error) {
- console.error('Invalid token:', error);
- }
- }
- // Redirect to signup if token is missing or invalid
- console.log('Redirecting to signup (no valid token)'); // Log reason for redirect
- return NextResponse.redirect(new URL('/signup', req.url));
- }
- export const config = {
- matcher: ['/workspace'], // Match all routes under /protected
- };
Advertisement
Add Comment
Please, Sign In to add comment