Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics Deeper into Routing with Express Statelessness, Setting and Reading Cookies

Rebecca Jensen
Rebecca Jensen
11,580 Points

Cookies are undefined?

I'm following the Statelessness, Setting and Reading Cookies tutorial, which has you remembering cookies via...

res.render('pageName', {name: req.cookies.username})

...but my cookies are returning as undefined. In the tutorial, we have a form for the user to submit their name, which is the cookie we want to store. I've done this and watched the cookies in the console, and I see my entry to the form flash in the cookie list, then become undefined.

Why is this? And how can I circumvent it?

Thanks!

Can you share your code where you set the cookie in the response to a POST request?

David Ray
David Ray
6,691 Points

from another question posted on here, I used Nick Trabue's answer as posted below and this worked for me

app.get('hello', (req, res) => {
     res.render('hello', {name: req.cookies['username']});
});

app.post('/hello', (req, res) => {
     res.cookie('username', req.body.username);
    res.render('hello', {name: req.cookies['username']});
});