Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda