protecting routes using middleware

PHOTO EMBED

Sun Jul 23 2023 14:24:17 GMT+0000 (Coordinated Universal Time)

Saved by @nelson22

src > middleware.ts

import { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export function middleware(request: NextRequest){
    // getting the current path
    const path = request.nextUrl.pathname;

    // set public path
    const publicPath = path === '/login' || path === '/signup';

    // set token
    const token = request.cookies.get('token')?.value || '';

    // check if user is logged in
    if(publicPath && token){
        return NextResponse.redirect(new URL('/profile', request.nextUrl));
    }

    // check if user is logged out
    if(!publicPath && !token){
        return NextResponse.redirect(new URL('/login', request.nextUrl));
    }
}

export const config = {
    matcher: [
        '/',
        '/profile',
        '/profile/:path*',
        '/login',
        '/signup'
    ]
}
content_copyCOPY