I am trying to redirect the user to the homepage when he tries to access the dashboard of the app without being authenticated, but the Route.push() is not working.
I tried to change Router.push('/') to Router.push('/hey') -> a page that does not exists, and this worked, the route changed. Also when I try to access a path like this Router.push('/auth/signin'), it doesn't work while Router.push('/auth') works
import { isAuthenticated } from "../helpers/auth";
import { Component } from "react";
import { Router } from "../routes";
class Ads extends Component {
// static async getInitialProps(ctx) {
// if (ctx && ctx.req) {
// console.log(ctx);
// //ctx.res.writeHead(302, { Location: `/` });
// ctx.res.end();
// } else {
// console.log("client side");
// console.log(localStorage.getItem("auth-token"));
// }
// }
handleAuthentication = () => {
if (localStorage.getItem("auth-token")) {
return true;
}
};
componentDidMount() {
if (this.handleAuthentication()) {
console.log("hey");
} else {
Router.pushRoute("/auth/signup");
}
}
render() {
return (
<div>
<p> Dashboard </p>
</div>
);
}
}
export default Ads;
It seems you were using next-router dependecy?
Try to use next/router
(default dependency from nextjs), it works fine in my code:
import Router from "next/router";
{ other code... }
Router.push("/auth/signup");