skip to Main Content

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


  1. 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

    if (!session) {
      redirect("/login?from=" + pathname)
    }
    

    Then on the login page, set the callbackUrl of signIn() options to this path or URL.

    import {useSearchParams} from "next/navigation"
    import {signIn} from "next-auth/react"
    
    const searchParams = useSearchParams()
    const from = searchParams.get("from")
    
    await signIn("google", {
      callbackUrl: from ?? "/"
    })
    
    Login or Signup to reply.
  2. you can Solve my using
    import { useRouter } from ‘next/router’;
    import { useState, useEffect } from ‘react’;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search