Does each imported module in a Next.js app run multiple times?

There is a common understanding that when a module is imported multiple times within a JavaScript program, it only executes once during the first import.

Informative article:

The concept is straightforward: each module is evaluated just once, meaning the module-level scope is only executed once. Subsequent imports of the same module skip re-evaluation and make use of the previously resolved exports.

This explains why code placed above a React component runs only once, as mentioned in the official documentation:

Certain logic should be executed only once when the application starts. By placing it outside your components...it ensures that this specific logic runs just once after the page loads in the browser.

My inquiry pertains to Next.js on Vercel:

Do imports run only once when the site is built, and not again thereafter?

Or does this behavior vary between static and dynamic routes (pages)? For example, a static page may execute an import only during build time, while a dynamic route triggers the import every time the page is visited in a browser?

Answer №1

Affirmative, in a Next.js application, modules are executed multiple times when they are imported.

Negative, imports do not solely execute once during the site's construction and then never again.

You can easily verify this in development mode. Within your module:

// main module file
import { v4 as uuid } from 'uuid'

[...]

console.log(`module import ${uuid()}`)

Upon inspecting the browser console, you will notice one output with a specific uuid and another output server-side with a different uuid. This occurs even if the module is imported just once from client-side code (for example, a hook).

Each time a visitor accesses your website, an import takes place on the client-side. On the server side, it is uncertain but likely that the module gets imported upon restarts, deployments of new versions, etc. While my understanding of Vercel's inner workings is limited, utilizing SSR could result in instances where multiple copies of your module run concurrently on the server 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

Utilizing Jquery to Pass an Optional Function to Another Function

I am currently working on a function that utilizes AJAX to submit data and then displays a dialog indicating whether the process was successful or not. Everything seems to be functioning smoothly, but I now want to add the capability of passing an addition ...

Generate a menu submenu allowing for interactive toggling and dynamic visualization of expandable/collapsible sections upon clicking, featuring visually

Looking for assistance in creating a dynamic menu with sub-menus that can expand upon clicking. The goal is to have an expandable menu structure where the user can click to expand or collapse certain sections. However, my current code is not functioning co ...

Issue encountered while compiling all handlebars templates into a single JavaScript file

Below is the structure of my folders: app └───templates ├───templ1.hbs ├───templ2.hbs └───templ3.hbs I am looking to compile (precompile) all templN.hbs handlebars template files into one templ.js file. However ...

Variable missing in the ExpressJs view

Hey there! I'm new to Nodejs and currently experimenting with it. I've been trying to convert some of my basic Python codes to JavaScript. In one of my projects, I am sending a get request to the YouTube API and receiving 50 results in JSON forma ...

I am having trouble implementing internal/inline styles on dynamic elements within NextJs

I am struggling with formatting a code snippet similar to this one: <p className="xyz" dangerouslySetInnerHTML={{__html: dynamicContent}}></p> In the dynamicContent variable, there is a string and an anchor tag. I want to apply some ...

The jQuery change event is not triggered for <input type="file"> when a file is dropped on the label

I am currently developing a drag and drop file uploader that can be activated by either clicking the label or dragging a file onto the label. The input field includes a jQuery on change event that is triggered when a file is selected. However, it only see ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

Concatenate data received from PHP to a JavaScript variable and return it

In my current app development project, I have the following code snippet. The variable valdat is sent to a specified URL, processed through a PHP file, and then returned to the app. How can I add the data displayed in the alert message to another variabl ...

Step-by-step guide to generating a Paypal Button using Vue 3 script setup

After going through the PayPal Developer Docs, I'm still struggling to understand how to integrate the PayPal Button into Vue.js. The code examples provided are unclear, and I can't determine if it's related to Vue 2, Vue 3, or even Angular. ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

What is the best way to use jQuery to retrieve information from one child element in an XML API in order to locate another child

Hi there, I'm new to jQuery and could use some help. I'm attempting to retrieve specific information like CPU and RAM details from a particular phone model. I've written the jQuery code, but I'm having trouble displaying the RAM and CPU ...

Customizing the attribute of an HTML tag using EJS or jQuery

Within my express server, I am rendering a page with the following data: app.get('/people/:personID', function (req, res) { res.render("people/profile", {person: req.person }); }); Inside my profile.ejs file, I can display the data within an ...

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

Creating a video game HUD effect using JavaScript and HTML5

In an attempt to recreate a video game HUD using HTML5, I have styled a div with CSS properties to resemble a game overlay. When a navigation link is clicked, the div should transition from a hidden state (display:none), then flash twice rapidly before fad ...

Embarking on the journey of launching an Angular application on AWS CloudFront

I have a Laravel PHP application that functions as an API accessed by an Angular single-page app. Currently, the Angular app is situated within the public folder, but I aim to separate it so I can deploy it through Amazon CloudFront. I came across this ar ...

Do not use Express.js to serve the index.html file

Encountered an issue when attempting to run my Express.js solution. Instead of opening my desired index.html file located in the client directory, it kept opening the index.jade file from the views folder with the message "Welcome to Express" on the browse ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

Is it possible to render a web page in C++ that includes JavaScript, dynamic html, and retrieve the generated DOM string?

Is there a way to fetch and extract the rendered DOM of a web page using C++? I'm not just talking about the basic HTTP response, but the actual DOM structure that is generated after JavaScript has executed (possibly after allowing it some time to run ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

Creating a dynamic menu structure by tailoring it to the specific elements found on each page

Currently, I am facing issues while attempting to generate a dynamic menu based on the elements present on the page. Is there a way to develop a menu using the following code structure?: <div class="parent"> <div class="one child" id="first"& ...