Next.js Discord

Discord Forum

How to storage data in server memory in Nextjs 13 app directory?

Answered
Alex Iglesias posted this in #help-forum
Open in Discord
Avatar
Hello! I would like to know how can I storage in the server memory a JSON. I want to save the JSON in the server, not in the client with localStorage or sessionStorage. I have been searching a lot on the Internet but I can't find anything useful.

You can checkout my post on StackOverflow for a more detailed description:

https://stackoverflow.com/questions/77133702/how-to-storage-data-in-server-memory-in-nextjs-13-app-directory

Thank you in advance
Answered by tafutada777
I know that it won't persist but I don't care, is just for a demo and learning purposes.
as you mensioned in SO, if it's your toy hobby project, you can use global variables as it runs on Node.js or V8 Isolates. as you said, if it is hosted on serverless platforms like Vercel and Cloudflare Worker, instances are short-lived, so global vars such as connection pooling won't work efficiently.
the same thing goes to auto scaling platform like Kubernetes, where instances are dynamically spun up and down.
In general, in production, you need to use Redis or Cloudflare Durable Objects(beta), you might want to play around with it.
View full answer

6 Replies

Avatar
I know that it won't persist but I don't care, is just for a demo and learning purposes.
as you mensioned in SO, if it's your toy hobby project, you can use global variables as it runs on Node.js or V8 Isolates. as you said, if it is hosted on serverless platforms like Vercel and Cloudflare Worker, instances are short-lived, so global vars such as connection pooling won't work efficiently.
the same thing goes to auto scaling platform like Kubernetes, where instances are dynamically spun up and down.
In general, in production, you need to use Redis or Cloudflare Durable Objects(beta), you might want to play around with it.
Answer
Avatar
as i mentioned above, global variables are server memory, heap memory. but it's not guaranteed that the memory are shared across http requests, because instances are short-live and multiple instances are up and running. in other words, if it is hosted on vps with a single instance(Node.js runtime), the memory, global vars, are shared across http requests.
Avatar
They are if you are running in a non serverless environment like a single instance of Node.js runtime
i tested it, it does share global variables in production. Its not working in development environment for the sake of hmr afaik