Next.js Discord

Discord Forum

next auth credential remember this device function.

Unanswered
American posted this in #help-forum
Open in Discord
AmericanOP
Hi, i'am trying to add a remember this device function on next auth. so when the user checked remember this device the session will expired in 30day, and if not checked it will expired in 1 day.

2 Replies

AmericanOP
for now i handle it like this..

authOptions.ts
export const authOptions:NextAuthOptions = {
    providers: [
        CredentialsProvider({
            name: "credentials",
            credentials: {
                username: {label: "Username", type: "text", placeholder: "username"},
                password: {label: "Password", type: "password"},
                isRemember: {label: "isRemember", type: "boolean"},
            },
            async authorize(credentials, req) {
                if(!credentials?.username || !credentials.password)
                    return null
                const user = await db.user.findUnique({
                    where: {username: credentials.username}
                })
                if(user && await bcrypt.compare(credentials.password, user.password)){
                    const expiresIn = credentials.isRemember === "true" ? 30 : 1
                    return {id:user.id, username: user.username, expiresIn: expiresIn}
                }
                return null
            },
        })
    ],
    session: {
        strategy: 'jwt'
    },
    pages: {
        signIn: "/auth/signin"
    },
    callbacks: {
        jwt: async ({ token, user }) => {
            if(user){
                token.username = user.username
                // user.expireIn days converted to milliseconds ( 24 hours * 60 minutes * 60 seconds * 1000 milliseconds)
                token.expiresIn =  (Date.now() + (user.expiresIn * 24 * 60 * 60 * 1000));
            }
            return token;
        },
        session: async ({session,token}) => {
            return session
        }
    },
    secret: process.env.NEXTAUTH_SECRET,
    debug: process.env.NODE_ENV === "development"
}
middleware.ts
export default async function middleware(req: NextRequest, event: NextFetchEvent) {
  const token = await getToken({ req });
  const isAuthenticated = !!token;
  if (req.nextUrl.pathname.startsWith('/auth/signin') && isAuthenticated) {
    return NextResponse.redirect(new URL('/', req.url));
  }
  if(token?.expiresIn && Date.now() > token.expiresIn){
    const response = NextResponse.redirect(new URL(`/auth/signin?callbackUrl=${encodeURIComponent(req.url)}`, req.url))
    response.cookies.delete('next-auth.session-token')
    return response
  }
  
  const authMiddleware = await withAuth({
    pages: {
      signIn: `/auth/signin`,
    },
  });

   // @ts-expect-error
  return authMiddleware(req, event);
}
export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)',] }


it's is a good way to do it or there is better way to do it?