Async issue in express endpoint

I am using express.js with pug view templates. The below code always returns a value from the previous session, for example if I type 5 it first shows 5, but then 5 when I type 10, 10 when I type 15 etc

router.post('/api/donate', (req, res, next) => {
  if (req.body.step === '1') {
      // steps
      res.cookie('amount', req.body.donation_amount, {
        maxAge : 3600000, 
        httpOnly : true
      });
      res.render('donate2', { req : req });

Async has been a sticking point for me. How would you guys force the res.render line to wait until res.cookie’s amount has been updated?

It doesn’t look like the problem is in this code. Can you show us the code that reads the cookie?

Sure, here is my pug template with the variable interpolation

extends layout

block content
    div.container
        h2 Payment details for your #{req.cookies.amount} donation

Thinking through this:

req.cookies.name is not immediately updated by res.cookie()

instead it uses an old value. I will try turning it into a session cookie to see what happens

The thing is your req is the request the user did just now, the cookie won’t be set until the render method is called. So the cookie will only be available on the next request.

It doesn’t make too much sense to use cookies in the same request anyway if you think about it. You need the current amount, you can just get it directly from req.body.donation_amount in your pug template.

1 Like

You are right. I thought of directly passing the info too. But I felt that pulling the data from the cookie was more robust (since it would act as a temporary data store). I see now that direct passing is still needed though

I think you’ll probably want to check in case there’s no donation_amount in the request, maybe the user did just opened the app, then you load it from the cookies or display a default value.