ololo
ololo

Reputation: 2026

How to access NextJS Router in class component

I have the following HOC in NextJS.

I wish to access the NextJS router via the withRouter HOC for class components as below.

import UserManager from "../managers/user_manager";
import LogInPage from "../pages/auth/login";
import React from "react";
import { withRouter } from 'next/router'

export default function EnsureAuthenticated(OriginalComponent) {
    class AuthHOC extends React.Component {
        constructor(props) {
            super(props);
        }
        componentDidMount() {
            this.loggedInUser = UserManager.getLoggedInUser();
        }
        render() {
            if (!this.loggedInUser) {
                this.props.router.push(LogInPage.routePath);
            }
            return <OriginalComponent />
        }
    }
    return withRouter(AuthHOC);
}

But this is the error I keep getting:

Server Error
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

What do I do differently to resolve this? Thank you.

Upvotes: 0

Views: 1987

Answers (1)

Arvind Pal
Arvind Pal

Reputation: 521

NextJS uses SSR, so During Pre-rendering (SSR or SSG) you tried to access a router method push (this.props.router.push(LogInPage.routePath)) which is not supported.

you should you use your following code in the componentDidMount method

if (!this.loggedInUser) {
      this.props.router.push(LogInPage.routePath);
}

like as below

  componentDidMount() {
            this.loggedInUser = UserManager.getLoggedInUser();

            if (!this.loggedInUser) {
                    this.props.router.push(LogInPage.routePath);
            }
        }

Upvotes: 1

Related Questions