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
A server redirection will always loads/refreshes up your client. Try to use a
/src/middleware.js
instead.Learn more about middlewares here (app router): https://nextjs.org/docs/app/building-your-application/routing/middleware
This might be the problem at the client side, Where the option you provide at client API functions like
signIn()
orsignOut()
you can specify like below to turn off the
redirect
option insignIn()
orsignOut()
funtion like below