1

Everything works perfectly fine one problem is that when I am logged In I am redirected to "/" page and if a user wanna go to "/login" or "/register" page even after being logged In they should be redirected to "/" page how can I add that feature in this code right now I am able get to "/login" page even after logged in but the page says localhost redirected you too many times error in the web page.

The code middleware.js :

import { NextResponse } from "next/server";
import { verify } from "jsonwebtoken";

export function middleware(request) {
  const secret = process.env.JWT_SECRET;
  const jwt = request.cookies.get("jwt")?.value;
  const path = request.nextUrl.pathname;

  if (!jwt && !["/login", "/register"].includes(path)) {
    return NextResponse.redirect(new URL("/login", request.url));
  } else if (jwt && (path === "/login" || path === "/register")) {
    try {
      verify(jwt, secret);
      return NextResponse.redirect(new URL("/", request.url));
    } catch (error) {
      return NextResponse.redirect(new URL("/login", request.url));
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/login", "/register", "/"],
};

I was trying successful login and register using JWT verify and NextJs

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Bipin
  • 53
  • 4

1 Answers1

0

I think verify(jwt, secret) is failing. it is throwing error. so you are running into catch block. In the catch block you are redirected to the "login` again. So, you are hitting

else if (jwt && (path === "/login" || path === "/register"))

because jwt is valid and path==="/login". since verify is throwing error, you are hitting the catch block so you are kinda in a loop

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Then how can I solve this problem ? – Bipin May 21 '23 at 14:48
  • do u confirm that `verify()` is throwing error. try to `console.log(error)` inside catch block. – Yilmaz May 21 '23 at 14:49
  • Yeah I got this error in terminal : ``` [JsonWebTokenError: secret or public key must be provided] { name: 'JsonWebTokenError', message: 'secret or public key must be provided' }``` – Bipin May 21 '23 at 14:52
  • that means `process.env.JWT_SECRET` is undefined. `console.log(secret)`. did you set environment variable correctly. – Yilmaz May 21 '23 at 14:54
  • Yeah you are right I am getting nothing and I have stored it in .env like this JWT_SECRET="secret123" NODE_ENV=development and I am able to access process.env.NODE_ENV but not able to get JWT_SECRET don't know why ? – Bipin May 21 '23 at 15:02
  • `JWT_SECRET=secret123` with out "" – Yilmaz May 21 '23 at 15:09
  • Thanks man the problem was I just started using NextJS 13 and we have to declare .env inside the nextconfig file but instead I defined it in .env thanks again. – Bipin May 21 '23 at 15:39
  • you are not done yet :) what if `verify` fails in the future for any other reason. you have to think about how to handle the `catch` block – Yilmaz May 21 '23 at 15:42
  • 1
    may be I will delete jwt cookie if verify failed and If got error, what would you suggest – Bipin May 21 '23 at 16:11
  • invalidation the jwt is a good idea. but in real world applications, if the token verification fails, that is a big security issue, so you should somehow inform the user. this is just edge case. – Yilmaz May 21 '23 at 23:49