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.

  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}`));
    

Now try send the request again and see what happen.

image.png


And now the cookies are shown as expected.


How to decode the JWT encoded key

As we encoded the Secure cookie but now, we need to use it we need a way to decode it.

  1. First create a new file name decodeCookies.js in /controllers/cookies/
    const jwt = require('jsonwebtoken');
    
    const DecodeCookies = (req, res) => {
    	const cookies = req.cookies;
    	const secureCookie = cookies.myCookieButMorePrivate;
    
    	const secret = 'mySecret';
    	const decoded = jwt.verify(secureCookie, secret);
    
    	return res.send(decoded.value);
    };
    
    module.exports = DecodeCookies;
    

    And don't forget to add the route to the router as /cookies/decode

  2. Try send the get request to localhost:4000/cookies/decode and observe the result

    image.png



  3. As you see the cookie value is decode to it original form
    the jet.verify() is a function to verify and decode the signed data. If the data has been change without correct secret key it will return errors.




How to clear Cookies?

Right now we can send and set cookies to users. Now if there is a scenario that we need to remove the cookies how can we do it? Let's start.

  1. Let create a file at /controllers/cookies/ name clear.js
    const ClearCookies = async (req, res) => {
    	const target = req.query.target;
    
    	try {
    		res.clearCookie(target);
    		return res.send(`\"${target}\" Cookie cleared`);
    	} catch (error) {
    		console.error(error);
    		return res.status(500).send('An error occurred, Cookie not cleared');
    	}
    };
    
    module.exports = ClearCookies;
    


    And also add the route as /cookies/clear then try sending get method to localhost:4000/cookies/clear with a target query.