0

I use Next.js. I have one file with code:

export let counter = 0;

In the first file of api route /api/test1 I add number to counter:

counter += 5;

In the seconds file of api /api/test2 I want to get updated a value of counter:

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

But I get 0;

How can I get the current counter value in seconds file?

p.s. I simplified the task, using the example of a counter.

1
  • Hi Uoloar ! Have you checked the below answer? Let us know please. Commented Feb 13, 2024 at 7:03

1 Answer 1

1

During development, and because of hot reload, Next.js clears the Node.js cache on every request, resetting any variable in memory.

So fare a solution is to use the global object, for example like so:

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 };

This is highlighted on this post.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.