What steps should I take to resolve the NextRouter "not mounted" error when deploying my Next JS 13 app on Vercel

I am encountering an issue while deploying my Next.js 13 app. The error message states:

Module not found: Can't resolve 'encoding' in '/vercel/path0/node_modules/node-fetch/lib'

Additionally, I am facing a "Next Router not mounted" error.

Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted
    at useRouter (/vercel/path0/.next/server/chunks/5225.js:12428:15)
    at useHybridHydrate (/vercel/path0/.next/server/chunks/5225.js:6566:45)
    at Object.useWrappedStore (/vercel/path0/.next/server/chunks/5225.js:6614:9)
    at AuthProvider (/vercel/path0/.next/server/chunks/9622.js:219:31)
    at Je (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js:121:272)
    at Je (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js:127:11)
    at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js:128:91)
    at Ke (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js:131:155)
    at Je (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js:122:215)
    at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js:128:91)

To address the first error, I tried running npm add -D encoding based on a suggestion from another StackOverflow thread but it did not resolve the issue. As for the second error, I am using next/navigation instead of the outdated next/router, yet the problem persists. Any assistance would be appreciated.

[EDIT]

Upon debugging my application, I discovered that the error is originating from the usage of nextWrapper in conjunction with Redux. I incorporated this due to having multiple slices in my app.

store.js

import { combineReducers, configureStore } from "@reduxjs/toolkit";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import menuReducer from "./slices/menuSlice";
import vehicleReducer from "./slices/vehicleSlice";
import blogReducer from "./slices/blogSlice";

const combinedReducer = combineReducers({
  menu: menuReducer,
  vehicle: vehicleReducer,
  blog: blogReducer,
});

const reducer = (state, action) => {
  if (action.type === HYDRATE) {
    const nextState = {
      ...state,
      ...action.payload,
    };
    return nextState;
  } else {
    return combinedReducer(state, action);
  }
};
const store = configureStore({
  reducer: reducer,
});

const makeStore = () => store;

export const wrapper = createWrapper(makeStore);

and in layout.js

import "../styles/globals.css";
import { AuthProvider } from "./AuthProvider";

function RootLayout({ children }) {
  //new change
  return (
    <html>
      <head />
      <body className="max-w-7xl mx-auto">
        <AuthProvider>{children}</AuthProvider>
      </body>
    </html>
  );
}
export default RootLayout;

authProvider.js

"use client";
import React from "react";

import { SessionProvider } from "next-auth/react";
import { ChakraProvider } from "@chakra-ui/react";
import { SkeletonTheme } from "react-loading-skeleton";
import { wrapper } from "../store";
import { Provider } from "react-redux";
import NextTopLoader from "nextjs-toploader";

export function AuthProvider({ children, ...rest }) {
  const { store } = wrapper.useWrappedStore(rest);
  return (
    <SessionProvider>
      <Provider store={store}>
        <ChakraProvider>
          <NextTopLoader color="#008080" showSpinner={false} />
          {children}
        </ChakraProvider>
      </Provider>
    </SessionProvider>
  );
}

During deployment, I encountered an error when using the Redux provider within layout.js, leading me to move it to authProvider.

Answer №1

npm install -D encoding

By adding it as a dev dependency, the issue you are facing during deployment may be resolved. I recommend trying the following command instead:

npm install encoding

This could potentially fix your initial error. Please inform us if this solution works for you.

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

Can someone clarify the actual version of webpack.js being used in my Ruby on Rails application with --webpacker=react configuration?

My tech stack includes Ruby 2.7.1, yarn 1.22.5, Rails 6.0.4.4, and node v16.13.1 I recently followed a tutorial on integrating React into my Rails project from this link The tutorial led me to install webpacker 4.3.0 automatically in my Gemfile.lock file ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

What is the best way to encapsulate a slider within a fragment to prevent the occurrence of the "Type 'Element[]' is not assignable to type 'ReactNode'" error?

I'm encountering an issue with a Slider component in a NextJs landing page template. Every time I try to map through an array within the Slider component, I receive an error. I've attempted to find solutions online and came across this related th ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...

Retrieving the latest state from the Redux storage in React-Native using the useSelector hook fails to provide the

I recently made the switch from the older version of redux (pre-2019) which utilized case and switch statements. The redux store updates correctly, as seen in the TextInput component. However, when I try to use the selected value from the updated redux sto ...

Struggling with connecting or executing queries in getStaticPaths/getStaticProps while incorporating Snowflake into NextJS

After spending some time experimenting with NextJS, I decided to take on the challenge of converting an application into prerender static pages using getStaticProps and getStaticPaths with [id].js files for each page organized in their individual folders ( ...

What is the procedure for verifying the type of an element using chai?

Is there a way to determine if an element is either an "a" tag or a "div" tag? I've tried the following code, but it's not working as expected: it('has no link if required', () => { const wrapper = shallow(<AssetOverlay a ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

Is there a way to integrate TypeScript with styled components to display suggested properties on the component?

Hey there fellow developers! I'm currently diving into the world of TypeScript and trying to get the hang of it. One thing that's bothering me is not being able to see recommended props on a styled component while using TypeScript. For instance ...

Is it possible to import Components into index.tsx from the containing directory of index.tsx?

Can React components be imported from within the same directory in a page? I am able to successfully import from outside the /pages/[...]/ directory. Importing from /components/[...]/ works without any issues, which is great for reusable components. Howev ...

Converting a base64 image to an image object in Node.js: A comprehensive guide

My frontend implementation utilizes React, where the input accepts image files. ... onImageChange = event => { if (event.target.files && event.target.files[0]) { let img = event.target.files[0]; //This is the image object //The ...

Why aren't the child elements in my React / Framer Motion animation staggered as expected?

In my finance application, I am creating a balance overview feature. To display the content, I pass props into a single <BalanceEntry> component and then map all entries onto the page. With Framer Motion, my goal is to animate each rendered <Bala ...

Difficulty Encountered in Rendering Component Using setTimeout Function

Having trouble figuring out why my component, enclosed in a setTimeout function, is not appearing on the DOM: const ContentMain = Component({ getInitialState() { return {rendered: false}; }, componentDidMount() { this.setStat ...

Exploring Next.js: A beginner's attempt at displaying basic JSON data

I'm having trouble updating and displaying the content of my JSON data in my React app. Despite trying various solutions, including adjusting the return value of functions and seeking help on forums, I still cannot get rid of the issue where an empty ...

Navigating to NextAuth's login page after signing in with NextJS

After spending the past 12 hours troubleshooting the same issue and scouring countless online forums, I am still unable to find a solution that meets my requirements. Despite following the NextAuth and NextJS tutorial for setting up authentication, I am s ...

Setting the state based on Promise values within a loop

I am currently facing a challenge in my React project where I am using axios to interact with an external API. The goal is to loop through the array of objects retrieved from the API call and utilize the values returned by a separate function within the ...

Navigating a page without embedding the URL in react-router-dom

In my application, I am utilizing react-router-dom v5 for routing purposes. Occasionally, I come across routes similar to the following: checkup/step-1/:id checkup/step-2/:id checkup/step-3/:id For instance, when I find myself at checkup/step-1/:id, I int ...

Error in React due to custom pagination indexing issue

When developing a custom Pagination component in React, I encountered an issue where the indexing restarts from "0" every time the page is changed using the next or previous button. What I want is for the index to start from the last position when clicking ...

Avoiding the creation of a history entry while switching languages on a Next.js website

I'm currently developing a Next.js project that includes a language dropdown feature for users to choose their preferred language. In the existing setup, we are utilizing the router.push method from next/router to update the language selection and red ...

How can I maintain form data submission to the server without triggering a redirect?

I am currently in the process of developing a web application that utilizes the Spotify API. My goal is to utilize the user input data to trigger calls to the Spotify API on the server and then relay the results back to the front end. However, I have encou ...