I'm trying to create a server-side authentication hook in Next.js
withAuth.tsx
import React from "react";
import { NextRouter, withRouter } from "next/router";
import { AuthContext } from "../contexts/AuthContext";
interface Options {
requiresAuth: boolean;
redirectsTo: string;
}
interface WithRouterProps {
router: NextRouter;
}
interface WithAuthProps extends WithRouterProps {}
const withAuth = (
Component: Function,
options: Partial<Options> = {
requiresAuth: true,
redirectsTo: "/something",
}
) => {
class WithAuth extends React.Component<WithAuthProps> {
user = this.context.user;
static contextType = AuthContext;
render() {
if (!this.user) {
if (options.requiresAuth) {
return this.props.router.push(options.redirectsTo!!);
} else return <Component />;
} else {
if (options.requiresAuth) return <Component />;
else return this.props.router.push(options.redirectsTo!!);
}
}
}
return withRouter(WithAuth);
};
export default withAuth;
index.tsx
import type { NextPage } from "next";
import withAuth from "../hooks/withAuth";
const Home: NextPage = () => {
return <div>Index</div>;
};
export default withAuth(Home);
And the full error message that I am getting:
Error: No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance
From Next.js documentation:
During Pre-rendering (SSR or SSG) you tried to access a router method push, replace, back, which is not supported.
In a class Component, move any calls to router methods to the
componentDidMountlifecycle method.
I suspect that the second point is where my issue comes from. But the thing is that I need to push the router from the render function. Is there any solution for this. Thank you.