skip to Main Content

I’m building a site based on this tutorial: https://nextjs.org/learn/dashboard-app/

At this section of the tutorial: https://nextjs.org/learn/dashboard-app/adding-authentication#protecting-your-routes-with-nextjs-middleware

There is code that manages a login using next auth

import type { NextAuthConfig } from 'next-auth';
 
export const authConfig = {
  pages: {
    signIn: '/login',
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
      if (isOnDashboard) {
        if (isLoggedIn) return true;
        return false; // Redirect unauthenticated users to login page
      } else if (isLoggedIn) {
        return Response.redirect(new URL('/dashboard', nextUrl));
      }
      return true;
    },
  },
  providers: [], // Add providers with an empty array for now
} satisfies NextAuthConfig;

The problem I’m having is at this part of the code (Response.redirect)

  } else if (isLoggedIn) {
    return Response.redirect(new URL('/dashboard', nextUrl));
  }

This returns you to where you were which is nice but it completely reloads the page and in my site I lose all state which isn’t nice

Is there a way to redirect back to the previous page in this fashion without the page reload? similar to a client side link so I don’t lose my state?

2

Answers


  1. A server redirection will always loads/refreshes up your client. Try to use a /src/middleware.js instead.

    export { default } from "next-auth/middleware";
    
    export const config = {
      matcher: ["/dashboard"],
    };
    

    Learn more about middlewares here (app router): https://nextjs.org/docs/app/building-your-application/routing/middleware

    Login or Signup to reply.
  2. This might be the problem at the client side, Where the option you provide at client API functions like signIn() or signOut()

    you can specify like below to turn off the redirect option in signIn() or signOut() funtion like below

    import { signIn } from "next-auth/react"
    
    signIn('credentials', { redirect: false, ...otherCredentials })
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search