[Fixed] Nextjs error occurred prerendering page "/" – Javascript

by
Ali Hasan
next.js reactjs

Quick Fix: In the Navbar component, export the component by adding export {Navbar} at the end of the file to make it available for use in other parts of the application.

The Problem:

When running npm run build on a Next.js app, an error occurs during prerendering of the homepage (/):

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token u in JSON at position 0
...

The app includes the following code:

page.js:

import Navbar from './components/navbar';

export default function Home() {
  return (
    <main className={styles.main}>
      <Navbar/>
    </main>
  )
}

navbar.js:

import React, { useState } from &#39;react&#39;;

&quot;use client&quot;;

export default function Navbar() {
  const [showNav, setShowNav] = useState(false);
  const [loggedIn, setLoggedIn] = useState(false);

  return (
    <nav ...>
      ...
    </nav>
  );
}

The error appears to be related to the use of useState in the Navbar component, which is not allowed in Server Components. Server Components must be marked with use client to allow the use of state hooks.

The Solutions:

Solution 1: Add Export Statement to Navbar

In the provided code, the ‘Navbar’ component is not exported. To resolve this error, add an ‘export’ statement to the bottom of the ‘navbar.js’ file:

// Add this to the bottom of the file.
export {Navbar};

By doing this, you declare that the ‘Navbar’ component should be made available outside the ‘navbar.js’ module. This allows you to import and use the ‘Navbar’ component in other parts of your application, such as ‘page.js’.

Q&A

How to fix: Error occurred prerendering page "/"?

You are not exporting the component in Navbar, only declaring it.

Video Explanation:

The following video, titled "Error occurred prerendering page | build export encountered error in ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Error occurred prerendering page | build export encountered error in NextJS. 6.4K views · 1 year ago ...more ...