When a user requests a protected route, I’d like to redirect them to the login page. After successful authentication, I want to redirect the user back to the originally requested protected route.
On next 12 it I used to do it like this
import { useRouter } from "next/router"
const router = useRouter();
const onSuccess = () => {
const prev = router.query.from as string;
router.replace(prev|| '/');
};
2
Answers
This answer assumes you’re using
next-auth
, but It’s the same in any way.It’s the same concept, when you redirect them to the login page just add a searchParam to the url
Then on the login page, set the callbackUrl of
signIn()
options to this path or URL.you can Solve my using
import { useRouter } from ‘next/router’;
import { useState, useEffect } from ‘react’;