Reputation: 287
Can't get this to work. I have a NextJS application with NextAuth. On each page, I do a getServerSideProps() where I check if user is logged in / has session, redirect to the page they want. If no session - send to an unauthorized page.
Basically, if user requests /page1 - and they're not authorized, it sends them to signin, trying to keep /page1 in a querystring of some sort, so after successful login - I can redirect them to the page the originally requested.
So I have something like
export async function getServerSideProps(context : any){
const session = await unstable_getServerSession(context.req, context.res, authOptions)
if (!session) {
//context.resolvedUrl = HAS THE REQUESTED PATH...
return {
redirect: {
destination: `/api/auth/signin?redirect=${context.resolvedUrl}`,
permanent: false,
},
}
}else{
return {
props: {
session,
}
}
}
}
I also see a callbacks API for NextAuth -> https://next-auth.js.org/configuration/callbacks - which has a "redirect" callback - but looks like it can only do url / baseUrl from params.
Can anyone lead me how to achieve this using NextAuth + NextJS.
Thank you.
Upvotes: 4
Views: 1561
Reputation: 66
With middleware and authjs v5, you can do something like the following:
import { auth } from "@/auth"
export default auth((req) => {
const isAuthenticated = !!req.auth;
const { nextUrl } = req;
//if the user isnt authenticated, redirect them over to the signin page
if (!isAuthenticated) {
const url = req.nextUrl.clone()
//set the search parameter callbackUrl to the url that was initially requested - this lets the user be redirected to the url they
//originally requested once they're signed in
url.search = 'callbackUrl=' + url.pathname
//force them over to the login page
url.pathname = '/api/auth/signin'
return Response.redirect(url);
}
})
export const config = {
matcher: ["/manager/:path*"],
}
Specifically, using the url.search property to set callbackUrl works for me to redirect the user to the requested page after login.
Upvotes: 0