Skip to content

Module imported in different files re-evaluated #49309

Open
@jesinmat

Description

@jesinmat

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: linux
      Arch: x64
      Version: #1 SMP Wed Mar 2 00:30:59 UTC 2022
    Binaries:
      Node: 17.9.0
      npm: 8.19.3
      Yarn: N/A
      pnpm: N/A
    Relevant packages:
      next: 13.4.1-canary.2
      eslint-config-next: 13.4.1
      react: 18.2.0
      react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

No response

Link to the code that reproduces this issue

https://github.com/jesinmat/next-reimport

To Reproduce

Build and run the project. Open the app in your browser. You should see the following:

Current ID: 1
<Change ID>

In the server log, you will see that a cache has been created (by importing lib/cache.ts):

Creating a cache
Loading data from database
Returning data 1

Now, click on the "Change ID" button. You should see the following in the server log:

Creating a cache
API request received
Setting data to 2

Now refresh the page. Client will still see 1 as the ID as there are now two caches, since it was imported twice and evaluated upon each import. This should not happen.

Describe the Bug

According to ECMAScript specification, importing a module from different places should only evaluate it once.
I wanted to use this fact to create a "cache", but it seems like the imported file is re-evaluated during imports from different files,
which makes it impossible to use as a singleton.

The file in question is located at lib/cache.ts and it's imported in app/page.tsx and pages/api/change/index.ts. Importing from these two files causes Cache constructor to be called twice, effectively exporting two completely separate instances of the class.

Expected Behavior

File lib/cache.ts is only evaluated once and the result is exported and shared between all places.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue was opened via the bug report template.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions