1

I want to open login page, when user is not logged in. But first opens the page index.js and only then sends it to the page login.js.

My code

export default function redirectTo(destination, { res, status } = {}) {
    if (res) {
        res.writeHead(status || 302, { Location: destination })
        res.end()
    } else {
        if (destination[0] === '/' && destination[1] !== '/') {
            Router.push(destination)
        } else {
            window.location = destination
        }
    }
}

And in _app.js

const {token} = useAuth()

useEffect(() => {
    if (!token) {
         redirectTo('/login', {})
    }
}, [])
4
  • In the useRouter documentation there is a redirect example.
    – Camilo
    Mar 20, 2021 at 14:19
  • there is example for redirect from one page to another, but i want open the site in login.js when user is not loggined, before open the index.js
    – Yervand
    Mar 20, 2021 at 15:35
  • 1
    I think you would need to implement a custom server for that.
    – Camilo
    Mar 21, 2021 at 0:21
  • where i must to call function getServerSideProps? In _app,js? const {token} = useAuth() useEffect(() => { if (!token){ getServerSideProps() } }, [token])
    – Yervand
    Mar 21, 2021 at 7:24

1 Answer 1

1

Your mistake :

Router.push(destination) ==> destination as a string does not do the job

Change it to:

Router.push({ pathname: destination })

Not the answer you're looking for? Browse other questions tagged or ask your own question.