add a searchParam in protectedRoute | nextAuth
Unanswered
Naeemgg posted this in #help-forum
NaeemggOP
I have some protected routes configured with next-auth in middleware matcher, My question is assume
all I want is to redirect users from where they came from everytime, For that I thought of adding a
/dashboardand /account both are protected routes. user comes by clicking a link https://my-web.vercel.app/dashboard and directly redirected to /login as user was unauthorized, So after user loggs in he'll be redirected to /account as I have called the signIn function like thisconst res = await signIn("credentials", {redirect:false, email: data.email, password: data.password });
if(res?.status===200){
router.push(`/${lang}/account`)
....all I want is to redirect users from where they came from everytime, For that I thought of adding a
searchParam in /login but unable to do it.2 Replies
NaeemggOP
Anyone.......!
@Naeemgg I have some protected routes configured with next-auth in middleware matcher, My question is assume `/dashboard`and `/account` both are protected routes. user comes by clicking a link `https://my-web.vercel.app/dashboard` and directly redirected to `/login` as user was unauthorized, So after user loggs in he'll be redirected to `/account` as I have called the `signIn` function like this
ts
const res = await signIn("credentials", {redirect:false, email: data.email, password: data.password });
if(res?.status===200){
router.push(`/${lang}/account`)
....
all I want is to redirect users from where they came from everytime, For that I thought of adding a `searchParam` in `/login` but unable to do it.
1. add the searchParams to the url in middleware when redirecting
2. grab the searchParams from the page props or with
return NextResponse.redirect(`/login?from=${req.nextUrl.pathname}`)2. grab the searchParams from the page props or with
useSearchParams() hookconst searchParams = useSearchParams()
const from = searchParams.get("from")
router.push(from || '/account')