Can't verify access token in middleware nextjs

98 views Asked by At

I am trying to verify my token in nextjs middleware using jose library. But if any case the code goes into the catch block it enter into a infinite loop and doesn't redirect to the login page.Actually, I have never authenticate token before, so I am kind of confused what I should do now. This problem specially happened when someone change the access token in the browser.This is my code.

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtVerify } from 'jose';

export default async function middleware(request: NextRequest) {
    const access = request.cookies.get("access")?.value;
    const url = request.url;
    const urlStartWithUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/open-bo-account`;
    const redirectUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/login/`;


    if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
        request.cookies.clear()
        return NextResponse.redirect(new URL('/login', request.url));

    } else if (access) {
        try {
            const secret = new TextEncoder().encode(
                "secret key"
            );
            const decodedToken = await jwtVerify(access, secret);
            if (decodedToken) {
                return NextResponse.next();
            }
            request.cookies.clear();
            return NextResponse.redirect(new URL('/login', request.url));
        } catch (error) {
            const cookiesBeforeClear = request.cookies.getAll();
            console.log("Cookies before clear:", cookiesBeforeClear);
            request.cookies.clear();
            const cookiesAfterClear = request.cookies.getAll();
            console.log("Cookies after clear:", cookiesAfterClear);
            return NextResponse.redirect(new URL('/login', request.url));
        }
    }
}

1

There are 1 answers

0
sourav singha On

The problem was in the else if block.it should be the following (access && request.nextUrl.pathname.startsWith('/open-bo-account')) Full code is like

import type { NextRequest } from "next/server";
import { jwtVerify } from 'jose';

export default async function middleware(request: NextRequest) {
    const access = request.cookies.get("access")?.value;
    const secret_key = `${process.env.SECRET_KEY}`

    if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
        request.cookies.clear()
        return NextResponse.redirect(new URL('/login', request.url));

    } else if (access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
        try {
            const secret = new TextEncoder().encode(secret_key);
            const decodedToken = await jwtVerify(access, secret);
            console.log(decodedToken)
            // const payload = decodedToken.payload;
            if (decodedToken) {
                return NextResponse.next();
            }
        }catch (error) {
            request.cookies.clear();
            return NextResponse.redirect(new URL('/login', request.url));
        }
    }
}