Next.js Discord

Discord Forum

Vercel: Logout route gets called randomly

Answered
borghese posted this in #help-forum
Open in Discord
Avatar
I've deployed a NextJS project to Vercel that uses iron-session and cookies to provide OAuth2 authentication with Discord.
As always, everything works in development, but when shipped in production some issues emerge.
Whenever I visit a page such as '/', everything works, I can even navigate trough different pages and it works as expected.
BUT, for some reason, after some time the /api/oauth/logout route gets called and the session gets deleted.
There are NO calls to that API route and NO middlewares that could potentially redirect the user to logging out.
I will be able to provide more code whenever someone replies but I literally have no idea where to check for errors...

/api/oauth/logout/route.tsx
import { defaultSession, SessionData, sessionOptions } from "@/lib/session/session";
import { getIronSession } from "iron-session";
import { NextApiRequest } from "next";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export const GET = async function GET(req: NextApiRequest) {
  const session = await getIronSession<SessionData>(cookies(), sessionOptions);
  if (session) {
    console.log("Session: ", JSON.stringify(session));
  } else {
    console.log("No active session.");
  }
  console.log("Request headers: ", JSON.stringify(req));

  session.destroy();

  return NextResponse.redirect(process.env.APP_URI as string);
}
Image
Answered by borghese
Found the solution myself.
Basically, [the <Link> component from next/link automatically prefetches the destination in the href](https://nextjs.org/docs/app/api-reference/components/link#prefetch:~:text=Prefetching%20happens%20when,client%2Dside%20navigations).
By fetching the /api/oauth/login route the user would get logged out without actually "clicking" the button.
Adding the prefetch={false} option to the <Link> component was sufficient to fix the issue.
View full answer

2 Replies

Avatar
I just noticed that even after logging in, when redirected to the main page (/), the /api/oauth/logout route gets called but fails with a CORS Error.
For some reason even two other routes get called without even reaching them in the broswer (see the 2 GET requests before the CORS error)
Image
Avatar
Found the solution myself.
Basically, [the <Link> component from next/link automatically prefetches the destination in the href](https://nextjs.org/docs/app/api-reference/components/link#prefetch:~:text=Prefetching%20happens%20when,client%2Dside%20navigations).
By fetching the /api/oauth/login route the user would get logged out without actually "clicking" the button.
Adding the prefetch={false} option to the <Link> component was sufficient to fix the issue.
Answer