0

I am a newbie with next-auth. my app still uses a frontend and backend separation, and I'm using CredentailProvider for login to obtain an access token from the backend server. when I fetch data from the API on the page and the API responds with a 401, I want to log out automatically. I noticed that signOut() is a client-side function, so I can't call signOut().

my sample code:

import auth from "@/lib/auth";

export default async function Page() {
  const session = await auth();
  const token = session?.accessToken;

  const data = await getData({
    token: token || "",
  });

  if (data.status === 401) {
    // I want to logout here

    return <p>Error: {data.error}</p>;
  }

  return (
    <>{data.result}<>
  );
}

I am using the Next-Auth v5

I can't call the signOut() function on SSR pages.

2
  • Perhaps clarify what SSR is/means here - probably not Sunny Side Response... Commented Jun 10 at 20:54
  • Server side render Commented Jun 11 at 0:31

2 Answers 2

0

I didn't work with Next's app directory too much so far but it would be helpful to see what's exactly happening in your @/lib/auth file.

By having a look at the docs of next-auth I could see that there is a REST API endpoint that you can trigger to sign the user out in the database:

https://next-auth.js.org/getting-started/rest-api#post-apiauthsignout

Handles signing the user out - this is a POST submission to prevent malicious links from triggering signing a user out without their consent. The user session will be invalidated/removed from the cookie/database, depending on the flow you chose to store sessions.

But I can imagine this already happened to your account if you get a 401. Otherwise I'd suggest you to provide a flag to the client so the client can identify that the signOut action needs to be called.

To run code on the client in SSR pages you need to put the code into a useEffect

Sign up to request clarification or add additional context in comments.

Comments

0

There's probably better ways to do what you're trying to do, but how about a logout page that will automatically call signOut and redirect the user to that page when needed?

Something like:

app/logout/page.tsx:

'use client';
import { useEffect } from 'react';

export default function LogoutPage() {
  useEffect(() => {
    signOut();
  }, []);

  return null;
}

and in your function:

import { redirect } from 'next/navigation';

...

if (data.status === 401) {
  return redirect('/logout');
}

If you have route guards set in place, by signing out your application should automatically redirect to a page that does not require authentication.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.