#NextAuth doesn't work well.

1 messages · Page 1 of 1 (latest)

plain plover
#

When I login first and change tab, it signs out.
When I login again, it works
Could you fix this?

dire sparrowBOT
#

Hi @plain plover. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

It sounds like you are experiencing issues with session persistence in NextAuth when switching tabs. This could be related to how cookies are being managed or how the client router cache is behaving. Here are a few steps you can take to troubleshoot and potentially fix this issue:

  1. Check Cookie Settings:
    Ensure that cookies are being set correctly and are persistent across tabs. You can verify this by inspecting the cookies in your browser's developer tools.

  2. Disable Client Router Cache:
    Sometimes, the client router cache can cause issues with session persistence. You can disable it by modifying your next.config.js as follows:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      experimental: {
        staleTimes: {
          dynamic: 0,
        },
      },
    }
    

    This ensures that every request hits the server, which might help in maintaining the session state.

    Source: Github Issue (closed): Is Middleware need to be cached? > Comments Part 1 (https://github.com/vercel/next.js/issues/65956)

  3. Ensure Proper Middleware and Redirect Handling:
    If you are using middleware for authentication, ensure that it is correctly handling the session tokens. Here is an example of how you might handle access tokens in middleware:

    import { NextResponse } from 'next/server';
    
    export const config = {
      matcher: '/((?!api|static|.*\\..*|_next).*)',
    };
    
    function setAccessTokenCookie(response, accessToken) {
      response.cookies.set('access', accessToken, {
        httpOnly: true,
        maxAge: 10 * 60 * 10, // 10 minutes
      });
    
      return response;
    }
    
    async function refreshAccessToken(request, origin) {
      const refreshCookie = request.cookies.get('refresh')?.value;
      if (!refreshCookie) return null;
#

const res = await fetch(process.env.BASE_URL + /auth/refresh, {
headers: { refresh: refreshCookie },
});

 if (!res.ok) return null;

 const { accessToken } = await res.json();

 return accessToken;

}

async function verifyAccessToken(request, origin) {
const accessCookie = request.cookies.get('access')?.value;
const refreshCookie = request.cookies.get('refresh')?.value;

 if (!accessCookie && !refreshCookie) return null;

 const res = await fetch(process.env.BASE_URL + `/auth/verify`, {
   headers: { access: accessCookie, refresh: refreshCookie },
 });

 if (!res.ok) return null;

 const { success } = await res.json();

 return success ?? null;

}


Source: **Github Issue (open): [NEXT-1088] After upgrading to 13.3 from 13.2 middleware is not working anymore > Original post Part 1** (<https://github.com/vercel/next.js/issues/48083>)

4. **Update `signIn` and `signOut` Methods**:
Ensure that your `signIn` and `signOut` methods are correctly handling redirects and session states. Here is an example:

```ts
export async function login(prevState: any, formData: FormData) {
  // ...existing code
  await signIn('credentials', { redirectTo: '/protected', email, password });
  // ...existing code
}

export async function logout() {
  await signOut({ redirectTo: '/' });
}

Source: [Github Issue (closed): Redirect URL not updating correctly in browser after successful redirect > Comments Part

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: