Next.js Build: An error was encountered while prerendering the page "/api/user"

Whenever I compile my Next.js 14 application using the app directory, I encounter the following error:

[Error]: Dynamic server usage: Page couldn't be rendered statically because it used `headers`. More details can be found here: https://nextjs.org/docs/messages/dynamic-server-error
    at l (/Users/joh/Documents/dev/waletoo/.next/server/chunks/185.js:30:30275)
    at u (/Users/joh/Documents/dev/waletoo/.next/server/chunks/185.js:30:26794)
    at s (/Users/joh/Documents/dev/waletoo/.next/server/chunks/185.js:30:20357)
    at p (/Users/joh/Documents/dev/waletoo/.next/server/app/api/user/route.js:1:1271)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/joh/Documents/dev/waletoo/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:41304 {
  digest: 'DYNAMIC_SERVER_USAGE'
}

An error occurred while prerendering page "/api/user". Find more information here: https://nextjs.org/docs/messages/prerender-error
Error: Internal Server Error
    at p (/Users/joh/Documents/dev/waletoo/.next/server/app/api/user/route.js:1:1442)

This is how I have defined my api/user/route route :

import { getServerSession } from "next-auth";
import connectDB from "@/src/mongoDB/connect";
import UserModel from "@/src/mongoDB/userSchema";
import { authOptions } from "@/src/utils/authOptions";

export async function GET() {
    await connectDB();

    try {
        const session = await getServerSession(authOptions);

        if (!session?.user?.email) throw new Error("Unauthorized");

        const userEmail = session.user.email;
        const userInformations = await UserModel.find({ email: userEmail });

        return new Response(JSON.stringify(userInformations));
    } catch (error) {
        console.error(error);
        throw new Error("Internal Server Error");
    }
}

Can you identify any issues in this setup?

Answer №1

The issue you are encountering is directly related to the usage of getServerSession in a statically generated page. Next.js typically handles server rendering in a single location, so any data fetching tied to a user must be recognized as dynamic.

To fix this problem, simply include export const dynamic = "force-dynamic" at the top of your page. This informs Next.js that the page utilizes dynamic server functionalities and cannot be statically optimized. Below is how you can update your code:

Javascript:

   export const dynamic = "force-dynamic";

import { getServerSession } from "next-auth";
import connectDB from "@/src/mongoDB/connect";
import UserModel from "@/src/mongoDB/userSchema";
import { authOptions } from "@/src/utils/authOptions";

export async function GET() {
    await connectDB();

    try {
        const session = await getServerSession(authOptions);

        if (!session?.user?.email) throw new Error("Unauthorized");

        const userEmail = session.user.email;
        const userInformations = await UserModel.find({ email: userEmail });

        return new Response(JSON.stringify(userInformations));
    } catch (error) {
        console.error(error);
        throw new Error("Internal Server Error");
    }
}

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

Using the TypeScript compiler API to determine the location in the generated code of a particular AST node

I am aiming to retrieve the specific TypeScript AST node's location (start and end) in the emitted JavaScript file. Consider this code snippet: const program = ts.createProgram(tsconfig.fileNames, tsconfig.options); const aNode = program.getSourceFi ...

Troubleshooting Vue.js data assignment issues

I'm attempting to implement basic form validation using Laravel 5.3 and Vue.js. Laravel controller: public function test(\Illuminate\Http\Request $request) { $this->validate($request, [ 'name' =&g ...

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Limiting the display of JSON data on a webpage using jQuery

I have a code snippet on my website that displays JSON data on an HTML page. The issue is that there is a large amount of data in the JSON file. How can I limit the number of movies (data) being displayed to just 5? function actors(actors) { return ` ...

jsGrid is failing to load within a Vue application that is utilizing static data

Struggling to implement jsGrid for a basic table with header sorting in my Javascript and Vue application. Having trouble loading the sample code with various components spread across different files. Here are the relevant parts: HTML (symbol-container is ...

What causes the active slide number to remain the same in Swiper JS pagination when using fractions?

I have been working on setting up an .image-slider__fraction block to display the active slide number out of the total number of slides. However, I am encountering an error in the JavaScript that says "Uncaught ReferenceError: myImageSLider is not defined" ...

Configurations passed to modules in RequireJS consistently return undefined

After attempting the solution provided in another Stack Overflow post, specifically this one, I found that it wasn't successful. The result always returned as undefined. This is the configuration in my HTML: <script type="text/javascript"> ...

Different ways to use functions with AngularJS, including the parsley and reset options

Here are two functions I use to reset error messages and form field values: $("#modal_form").parsley().reset();//This only resets error messages, not form field values $("#modal_form")[0].reset();//This only resets form field values, not error messages I ...

Unable to dial phone numbers when clicking 'Click to call' link on Android devices

Within my Cordova android application, I have a link set up like this: <a href = "tel:011123456789">Click to Call</a> While this click-to-call functionality works smoothly in IOS, it seems to be hindered in Android by an issue such as: 11- ...

What is up with this strange JavaScript variable string / DOM selection?

I'm facing a strange issue with a variable that appears to be a string when alerted, but in the console, it is actually a DOMSelection presented in tree form. How can I retrieve the actual string value from this console output? DOMSelection anchorNod ...

When using Vue3 along with Axios.post, the data is being serialized incorrectly

Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API. The following code snippets attempt to achieve this: // Attempt # 1 let re ...

The Ajax call was successful but the callback function failed to return

I've been encountering some challenges with a small application I'm developing. After successfully setting it up to automatically populate one field with the same value entered in another field, I decided to integrate an AJAX request into the scr ...

Coloring the table upon selecting a checkbox using AJAX, JavaScript, and JSP

How can I adjust the color of the entire table (every row of the table)? Currently, I can only change the color of the first row of my table. Here is my color function in JSP: function changeColor(rowID){ var row = document.getElementById(rowID); ...

Determine the mean value from an array of JSON objects in an asynchronous manner

Can you help me calculate the average pressure for each device ID in this JSON data set? [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "P ...

acquiring data via fetch (transferring information from javascript to php file)

I'm completely new to using fetch and not familiar with Ajax. Currently, I am attempting to transfer data from a JavaScript file (node.js server) to a PHP file (Apache server). The data being sent consists of 2 JSON values labeled as "a" and "b". T ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

PHP is unable to decode JSON that has been converted from JavaScript

When I send an array as a POST request, I first convert it to JSON using the JSON.stringify() method. However, I encountered an issue when trying to decode it in PHP. // JavaScript var arr1 = ['a', 'b', 'c', 'd', & ...

'The object of type '{}' does not support indexing with a 'string'

I am currently working on a React component that dynamically generates an HTML Table based on an array of objects. The columns to be displayed are specified through the property called tableColumns. While iterating through the items and trying to display ...

Retrieve the date information from the <td> element, if it exists

There are numerous rows in the table. The table cell labeled "dates" may contain either a specific date or the word "Permanent". If there is a date present and it happens to be greater than today's date, it needs to be highlighted in red. I attempted ...