Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
Next.js "no router instance found" in HOC authentication hook

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 componentDidMount lifecycle 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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda