Search code examples
javascriptreactjssessionnext.jsnext-auth

How to increase session expiration time based on user selection in NextAuth?


I am using Next-Auth for authentication in a Next.js app, I am using a Credentials provider. On the login page, there is an option for users to remember their password.

When this option is selected, I want to increase the session expiration time. If it is not selected, the expiration time should be set to 24 hours.

Login.js code:

  const handleSubmit = async (e) => {
    e.preventDefault();

    const res = await signIn("credentials", {
      redirect: false,
      username: username,
      password: password,
      rememberPassword: checked,
    });
    if (res?.error) {
      console.log(res.error)
    } else {
      push("/");
    }
  };

[...nextauth].js code:

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "credentials",
      async authorize(credentials) {
    ...
    //I can access rememberPassword here, for example :
    const rememberPassword = credentials.rememberPassword;
      },
    }),
  ],
  secret: SECRET_KEY,
  jwt: {
    secret: SECRET_KEY,
    encryption: true,
  },
  session: {
    jwt: true,
**    maxAge: req.body.rememberPassword ? 15 * 24 * 60 * 60 : 24 * 60 * 60, //I want something like this**
  },
};
export default NextAuth(authOptions);

I am having trouble accessing the rememberPassword in the session property.


Solution

  • You can use the advanced initialization to instantiate the options dynamically. To set the session expiration time, you can do so:

    // pages/api/auth/[...nextauth].js
    
    import NextAuth from "next-auth";
    
    export default async function auth(req, res) {
      // Do whatever you want here, before the request is passed down to NextAuth
      return await NextAuth(req, res, {
        // Other options go here 👈🏽
        session: {
          jwt: true,
          // 👇🏽 Your dynamic session
          maxAge: req.body.rememberPassword ? 15 * 24 * 60 * 60 : 24 * 60 * 60,
        },
      });
    }