Encountering Problem with NextJS and Typescript when Attempting to Import Protected Authentication to a Page

When I try to use my protected.tsx file on a page, I encounter an error message stating:

Server Error

Error: Attempted to call the default export of protected.tsx from the server, but it should only be used on the client side. Invoking a client function from the server is not possible; it can only be rendered as a component or passed as props to a client-side component.

'use client';
import React from 'react';
import { useUser } from '../context/user';
import { useRouter } from 'next/navigation';

interface ProtectedProps {}

const withProtected = (WrappedComponent: React.ComponentType<ProtectedProps>) => {
  const WithProtected: React.FC<ProtectedProps> = (props) => {
    const router = useRouter();
    const user = useUser();
    const { uid } = user;

    if (typeof window === 'undefined') {
      return null;
    }

    console.log({ uid });

    if (!uid) {
      router.replace('/');
      return <></>;
    }

    return <WrappedComponent {...props} />;
  };

  return WithProtected;
};

export default withProtected;

The code snippet below is from the page that is causing the error:

import React from 'react';
import withProtected from '../hoc/withProtected';

const StorePage: React.FC = () => {
  return (
    <div>
      <h2>Diecast Page</h2>
    </div>
  );
};

export default withProtected(StorePage);

If anyone can help me solve this issue, I would greatly appreciate it. Thank you!

Answer №1

Make sure you are importing the useRouter from the correct package. The error message indicates that it is being imported from next/navigation instead of next/router.

import { useRouter } from 'next/router';

Furthermore, the withProtected higher-order component (HOC) is unable to verify the user's login status during SSR (server-side rendering), so it should only be executed on the client side.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing the NextPage Typescript Type: A Step-by-Step Guide

I'm working on a NextJS dashboard with role-based access control and I need to pass an auth object to each page from the default export. Here's an image showing an example of code for the Student Dashboard Home Page: Code Example of Student Dashb ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

Troubles with NextJS and TailwindCSS Styling

I encountered a strange issue when I used the component separately. Here's how the code looked like: <> <Head> <title>Staycation | Home</title> <meta name="viewport" content="initial- ...

Automatically shift focus to the next input when reaching the maximum length in Angular

Looking for a smoother way to focus the next input element in Angular without manually specifying which one. Here's my current HTML setup... <div class="mb-2 digit-insert d-flex align-items-center"> <div class="confirmation-group d-flex"&g ...

The rewrites feature does not seem to be functioning properly for URLs outside of the

Configuring next.config.js The code snippet below has been added to our next.config.js file. Upon testing, we noticed that it is redirecting to the stackoverflow website. async rewrites() { return [ { source: "/test", ...

This component is not compatible with JSX syntax and cannot be used as a JSX component. The type '() => Element' is not suitable for JSX element rendering

My Nextjs seems to be malfunctioning as I encountered the following error in a Parent component. Interestingly, the Spinner Component remains error-free Spinner.tsx export default function Spinner() { return ( <div className='flex ...

React typescript - Error: Type 'boolean' is not compatible with the expected type

Check out this demo This is a simple React application built with Typescript. Currently, I am experimenting with React's Context API. I have set up a context named ThemeContext which holds basic theme styling values to be used across different comp ...

Deactivate the button until the input meets validation criteria using Angular

What I'm trying to achieve is to restrict certain input fields to only accept integer or decimal values. Here's the code snippet that I currently have: <input type="text" pattern="[0-9]*" [(ngModel)]="myValue" pInputText class="medium-field" ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

How to Decode JSON Data in Angular 2/4 with the Help of HttpClientModule

I am receiving this JSON structure from my asp.net core API: { "contentType": null, "serializerSettings": null, "statusCode": null, "value": { "productName": "Test", "shortDescription": "Test 123", "imageUri": "https://bla.com/bla", ...

Is it possible to evaluate a conditional in Angular after retrieving values from a subscription in an observable?

Objective: Verify conditional statement after retrieving data from an array Attempts Made: I explored various articles on SO with similar queries, but they didn't quite match my situation. I need to ensure that the entire Array is populated before ev ...

how to use all parameters except the first one in TypeScript

Is there a way to reference one function's parameter types in another function, but only use a subset of them without repeating the entire list of parameters? //params of bar should be same as foo, except p1 should be a different type function foo(p1 ...

Structured similar to a map with typed elements

As a beginner in Typescript, I am delving into creating a typed map structure where the values are associated with specific keys. This can be demonstrated through pseudo JS code without types: const propertyA = "PropertyA"; const propertyB = "PropertyB"; ...

Deleting the access token stored in the cookie prior to making an axios request

I've been facing a challenge in a Vue project where the request headers have become too large for our servers to handle, resulting in 413 error codes. Using JWT bearer tokens, I can see that the token is included in the request as the Authentication ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Leverage the power of useOptimistic to streamline the process of creating,

Exploring the new useOptimistic hook, I aimed to extend its functionality beyond simple setState calls to incorporate create, update, and delete operations. Given the limited availability of examples showcasing use cases for this nascent hook, I seek input ...

What is the best way to find the clinic that matches the chosen province?

Whenever I try to choose a province from the dropdown menu in order to view clinics located within that province, an error 'TypeError: termSearch.toLowerCase is not a function' pops up. This part of the code seems confusing to me and any kind of ...

The 'next-auth/react' module is missing when creating a custom email sign-in page using next-auth

Currently, I'm developing a NextJs application with next-auth to handle the authentication process. I have successfully implemented Email Sign In using next-auth's default pages. However, my goal now is to create a custom sign-in page. Following ...

I'm curious about the origins of the "readme" field within the artifact registry file

Within our private npm registry on Azure, we house our own npm package alongside the npmjs packages. One particular package, @typescript-eslint/parser, has caused our pipelines to fail during the npm install task due to a SyntaxError: Unexpected end of JSO ...

Angular/TypeScript restricts object literals to declaring properties that are known and defined

I received an error message: Type '{ quantity: number; }' is not assignable to type 'Partial<EditOrderConfirmModalComponent>'. Object literal may only specify known properties, and 'quantity' does not exist in type &ap ...