#Persist variable API handler folder

3 messages · Page 1 of 1 (latest)

stable oxide
#

Hi all, I need to persist this variable across multiple request methods. I only have access to it in GET and need to persist it to be used in the following POST request.
Here is the code...

In the GET method, I need access to variable "hi", which returns undefined. Obviously because its out of scope but I need it to be declared in the POST (as I'm getting the actual request from the POST request body)
A few things to note:

  1. I need data from the post request body in future requests, so it can't be declared elsewhere
  2. Because of a technical limitation of what I'm working with, they do need to be separate statements (can't be strung together with || or otherwise)
export default function handler(req, res) {
    if(req.method ===  'POST') {
        var hi = req.body
    }
    if (req.method === 'GET') {
        console.log(hi)
    }
}

Thanks in advance!

bold sluice
#

Can I ask what this technical limitation is?
Understanding the circumstances might help finding a better solution.

I can give you a general answer, which is more complex than it should be:

API routes in Next.js are stateless. You cannot access a previous request.
What you can do is saving the previous request in some kind of database or cache.
I recommend setting up redis for this kind of stuff.
On the POST request, save your variable hi to redis. You need some unique key to identify the user, e.g. from a session cookie or something. On GET, you can retrieve the variable from redis using the same key.

stable oxide
#

The technical limitation is that the API being used has to do with printing a physical print job to a printer, it requires that the requests are separate.

We actually just implemented this successfully thanks to an answer in another discord, it involved declaring an empty variable out of scope and setting it in scope. Seems to work fine.

I'll look into redis for more of a long term solution. Cheers!