`UseRouter` Caches the Cookies should I use `redirect`

18 Views Asked by At

Login Flow:

  • Successful login saves a cookie with user information.
  • I programmatically redirect to the dashboard using router.push('/dashboard'). However, this redirection is unreliable, sometimes working and sometimes not.

Logout Flow:

  • Logout removes the cookie.
  • The user is redirected to the login page using router.push('login'), which works as expected.
  • Inconsistent Access:
  • Even after logging out (and removing the cookie), if the user had previously accessed the dashboard, they can still access it despite not being authenticated.

The documentation indicates that the Next.js Router Cache cannot be disabled entirely, with only "hacky refreshes" as a workaround Router Cache. This approach feels wrong . I explored using server-side redirection within a login flow through a server action (redirect). This resolves the inconsistency but doesn't this add an extra server call, potentially impacting performance, especially for a large-scale system with a separate backend?

'use server'
 
import { redirect } from 'next/navigation'
 
export async function navigate(data: string) {
  redirect(data);
}

Is there a recommended approach to address these navigation issues while maintaining optimal performance and adhering to best practices for a large-scale Next.js application? Can we leverage the Router Cache effectively while ensuring proper authentication checks?

0

There are 0 best solutions below