Next.js Discord

Discord Forum

Is this an acceptable way of protecting routes using the middleware while doing auth with passport

Answered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
Hi, so I recently switched to using PassportJS for the first time and it's been alright so far. I'm using the following middleware function to protect routes in my Next.js application:
export async function middleware(request: NextRequest) {
  const authCookie = request.cookies.get("connect.sid")?.value;

  // Not logged in
  if (!authCookie) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  try {
    const getMeRequest = await axiosInstance.get("/auth/me", {
      headers: {
        Cookie: `connect.sid=${authCookie}`,
      },
    });

    // Valid session
    const response = NextResponse.next();
    response.headers.set("X-User-Data", JSON.stringify(getMeRequest.data));
    return response;
  } catch (err) {
    if (err instanceof AxiosError && err.request.status == 401) {
      // Invalid session
      return NextResponse.redirect(new URL("/login", request.url));
    } else {
      // Unknown error
      return NextResponse.redirect(
        new URL("/unknown-error?type=auth", request.url)
      );
    }
  }
}

export const config = {
  matcher: "/protected-routes/:path*",
};

Is this approach correct, or are there better practices for handling route protection and authentication with PassportJS in a Next.js application? Also, are there any potential security concerns or improvements that can be made to this implementation?

27 Replies

@Sloth bear it's almost correct, I see one flaw and one question
What's the /auth/me route
Does that just validate the cookie and is an api route?
Sloth bearOP
@Arinji the /auth/me route is basically a route that returns the currently logged in user's information such as username, display name, avatarUrl, etc when called
only if the session cookie is valid though
Ah ok nice, so you don't need to pass the cookie
You can just get cookies in api routes
It's not a flaw, just not needed
The flaw is setting data in the middleware
Like in your headers
The issue with headers is that they are publicly readable and also modifiable
Sloth bearOP
wait so if I just call /auth/me in the middleware without manually passing the cookie in it'll still work? I thought cookies will only be passed to the /auth/me if the request was made from the client and the middleware is server-sided no?
Answer
Sloth bearOP
interesting, thanks for pointing that out for me. I'm currently hosting the backend in a separate server on (Fastify with PassportJS)
The api route isn't on your nextjs site?
Sloth bearOP
nope
Oh yea then pass cookies
My bad lol, I thought it was on your nextjs site
Sloth bearOP
alright it's my fault I should have mentioned it xD
@Arinji Go through this for the headers stuff btw
Sloth bearOP
Will do, thanks a lot of btw
Basically instead of just passing along user data inside the middleware, make a function which decrypts the cookie and call that in any route or page you need
Much more secure
@Sloth bear Will do, thanks a lot of btw
No worries, mark a solution
Sloth bearOP
done, dunno which message to mark tbh xD
No worries, anything which points to the general fix works