What is the best way to access a shared object or variable across multiple files in TypeScript with Next.js?

I'm working with Next.js and have a single file containing the following code:

export let counter = 0;

In the first API route file /api/test1, I increment the counter by 5 like this:

counter += 5;

In the second API file /api/test2, I try to access the updated value of the counter:

console.log('counter', counter); // 5

However, I keep getting 0 instead;

Is there a way for me to access the current value of the counter in the second file?

p.s. This is a simplified version of my issue, using a counter example.

Answer №1

Throughout the development process, Next.js employs hot reload functionality to clear the Node.js cache with each request, effectively resetting any variables stored in memory.

As a workaround, one option is to utilize the global object, as demonstrated below:

class Counter {
  private count: number;

  constructor() {
    this.count = 0;
  }

  increment() {
    this.count++;
  }

  decrement() {
    this.count--;
  }

  getCount() {
    return this.count;
  }
}

let counter: Counter;

declare global {
  var counter: Counter;
}

if (process.env.NODE_ENV === "production") {
  counter = new Counter();
} else {
  if (!global.counter) {
    global.counter = new Counter();
  }
  counter = global.counter;
}

export { counter };

You can find more information about this approach in this post.

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 please help troubleshoot my ajax code?

My ajax function is calling a php page, but I keep encountering an issue where the error function is being triggered instead of the success function. What could be causing this unexpected behavior? Here is my ajax code: function register() { $.ajax({ ...

How can I prevent all code paths from causing errors in Typescript with Vuex?

It is possible that I may have overlooked specifying the return type in this function. However, I am unsure of how to adjust it. Please help me preserve the original function while migrating it to TypeScript. Your assistance and insights are greatly appr ...

I am encountering an error where authManager is not defined

I am encountering difficulties with authentication through Auth0. An error message stating "authenticate is undefined on the authManager" keeps appearing. The authManager is supposed to be injected into the authService, and both are added in the app unde ...

Adding basic data to an array dynamically

I am interested in creating an array with just one value inside it on the spot without having to use a variable. The following code achieves that using a variable: var arr = []; arr.push('test'); console.log(arr); // correctly logs ["test"] How ...

Bringing in the component's individual module

I encountered the error message in my Angular application - Can't bind to 'formGroup' since it isn't a known property of 'form' - and managed to resolve it by including the import import { AddEditModule } from './add.edit ...

ReactJS frontend is experiencing issues resolving a significant number of its node modules all of a sudden

After dedicating multiple weeks, on and off, to developing this application, I encountered a frustrating issue today. Everything had been running smoothly until now - I followed my usual setup process, installed all modules using npm install, and initializ ...

Manipulating <param> input using <button>

Is there a way to dynamically change the value of the second <param> tag using a <button> element? Here is the code snippet: <object type="application/x-shockwave-flash" id="dp_flash" name="dp_flash" class="placeholder_class" data="tooafra ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Issue with logical operator ""!"" functionality in ejs file

Take a look at this code snippet: <% if( !title || title!=="login"){ %> <div class="dashboard-main-cont"> <div class="navigation-option"> <a class="btn btn-primary navbtn" href=& ...

Encountered the error 'unable to read property 'then' of undefined', even though a Promise was returned

I'm encountering a common issue that has me stumped. The problem arises when I attempt to call a function that makes a GET request, processes the returned JSON, and then returns a Promise. When I try to print the parsed JSON data using this Promise, ...

Reset radio buttons upon submission without encountering any issues

How can I clear the radio button values in React without encountering errors in NextJS? I was able to successfully do it for other fields, as shown in the example below... <div className="col-md-6"> <label className="col-md-12 c ...

The constructor THREE.OrbitControls is not valid and I am unsure how to proceed

I've been attempting to incorporate OrbitControls into my project, but I keep encountering an error when trying to use the following line of code: var controls = new THREE.OrbitControls( camera, renderer.domElement ); Despite installing three.js and ...

Generate the maximum capacity 3D box that can be inscribed within a set of points

I am working with a 3D mesh composed of a collection of 3D points (vertices) and a series of faces (connections between points). Q1 Is there a method to determine the largest inscribed box (volume) that can fit inside the mesh? [OP] Greetings everyone, ...

How to Overcome Read-only HTML Components in Selenium with Python?

I am working on automating a task using Selenium in Python, and part of it involves selecting a date. The website I am testing has an input box for date selection that displays a standard date table when clicked. Unfortunately, the input text box is read- ...

How can you animate a MUI v4 Grid element using CSS transitions?

I was exploring the potential of using breakpoints in the MUI v4 component to control the visibility of items in my Grid System. How can I create a smooth CSS transition for b, transitioning from 0px to a defined breakpoint size of 3 for xl? Using % works ...

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

What steps can be taken to capture and store all console logs, errors, and warnings in a text file when a button is clicked?

My current project generates warnings, logs, and errors in case of any issues. I would like to provide users with a button that allows them to click and download the console.log data as a text file. Whether it is through a browser extension or using JavaSc ...

What is the proper way to insert a JavaScript file into jQuery code using the script tag?

I need help integrating a JS file into jQuery scripts to manipulate data retrieved from a database using $.ajax. I want to perform actions without refreshing the page. For example: $.ajax({ type: 'POST', url: "content.php", data: {vals: " ...

What is the process for transferring items using ref ObjectId's?

https://i.sstatic.net/pi6js.pngI'm currently in the process of developing a small personal betting website. I have successfully created Arrays of ObjectId's within each collection that reference one another. However, I am facing challenges when i ...

Angular 6 allows for the use of radio buttons to dynamically enable or disable corresponding fields

Here is the HTML code for a row containing radio button selections: <div class="form-row"> <div class="col-md-3 mb-3"> <div class = "form-group form-inline col-md-12 mb-3"> <div class="form-check form-check-inl ...