Skip to main content

Using Cookies

How to use cookies

Now as we can send cookies, I'll show you an example of how to get that cookies from user and use it.

const ShowCookies = (req, res) => {
	const cookies = req.cookies;
	res.send(cookies);
};

module.exports = ShowCookies;
  1. First let's create new file at /controllers/cookies name showCookies.js
    const ShowCookies = (req, res) => {
    	const cookies = req.cookies;
    	res.send(cookies);
    };
    
    module.exports = ShowCookies;
    


  2. Also add the routes as /cookies/show in your cookiesRouter file.
  3. Now try get the locahlost:4000/cookies/show



    image.png

    Right now, you will see that the cookies you have isn't show on the response.


  4. Install the cookie-parser by npm i cookie-parser and use it in the index.js as show:
    const express = require('express');
    const cookieParser = require('cookie-parser');
    
    const app = express();
    const port = 4000;
    
    app.use(cookieParser());
    
    app.get('/', (req, res) => res.send('Hello World!'));
    
    app.use('/cookies', require('./routes/cookies'));
    
    app.listen(port, () => console.log(`Server running on port ${port}`));