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', {})
}
}, [])