Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expires session automatically after 1 hour in nextjs auth?

I am trying to expire the session automatically after 1 hour without success.

Currently, I am trying to set up a custom session.expires in session callback based on backend JWT token:

        async session({ session, token }) {
            const userId = token.sub

            const user = [...logic to populate the 'user' variable]

            session.accessToken = token.accessToken as string
            const payload: { exp: number } = jwt_decode(session.accessToken as string)

            session.user = user
            session.expires = new Date(payload.exp * 1000).toISOString()
            return session
        },

If I keep the browser window open after login, after 1 hour the user seems to disconnect because you can see that the object received from the endpoint "/api/auth/session" is empty, however, when reloading the page the session is repopulated with the expires property in the past.

{
    "user":{},
    "expires":"2022-05-19T07:21:07.000Z",
    "accessToken":"ACCESS_TOKEN_GOES_HERE"}

PS: The "user" and "accessToken" properties are correctly populated. I omitted it for security reasons.

like image 338
Émerson Felinto Avatar asked Dec 11 '25 04:12

Émerson Felinto


1 Answers

I've had the same requirement and I have been able to achieve this be setting a different key in the user object (since I also needed this in the user session) in the session instead of "expires" since nextAuth will automatically rotate the value of expires key when you refresh the page.

Set the session expiry value in the NextAuth session callback in the [...nextauth].ts file as below.

callbacks: {
  ....
  async session({ session, token }) {
    session.user = token.user;

    if (!session.user.session_expiry) {
      // set expiration to 12 hours for now
      const exp = new Date(new Date().getTime() + 12*60*60*1000).toISOString(); 
      session.user.session_expiry = exp;
    }

    return session;
  },
}
...

In your client code, you will need to check this expiry and call the signout method of nextAuth.

const { status, data: sessionData } = useSession();

const { user: { session_expiry: sessionExpiry = null } = {} } =
  sessionData || {};


useEffect(() => {
  const isSiteSessionExpired = sessionExpiry || new Date(sessionExpiry) < new Date();
  if (status === "authenticated" && isSiteSessionExpired) {
     signOut();
  }
}, [sessionExpiry, status]);

This should force the user to signout if the session has expired.

Bonus : If youre using typescript, use the below code to get type check for the session_expiry variable.

import { type DefaultSession } from "next-auth";

type UserWithSessionExpiry = {
  session_expiry?: string;
} & DefaultSession["user"];

declare module "next-auth" {
  interface Session {
    user: UserWithSessionExpiry;
  }
}
like image 158
Ashwin Valento Avatar answered Dec 15 '25 00:12

Ashwin Valento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!