🍪🍪 Cookies with Express.js, Nodemon, ESM, Cookie Parser and Cookie Session

Rodrigo Figueroa
Geek Culture

--

Hi! This is a new post regarding Express.js, and for me, it is new to use Cookies with Express.js, but yeah! We will use Cookies and send it to the client and adding a little security. OK, let’s Bake these Cookies!!🍪🍪

Initiate NPM and install Express.js

First of all, we need a directory called bake_cookie (funny name 😁) then we need to initiate our package.json with this command

npm init -y

Then we need to install Express.js with this command

npm i express

Install nodemon and esm NPM packages

Nodemon is a utility to reload the server if you update tour server.js file and esm is a ECMAScript module loader that can helps us to use the import from ES6.

npm i nodemon esm

And in our package JSON we have to add this command to the package’s json scripts

Example command to run nodemon and esm
Example command to run nodemon and esm
"start": "nodemon -r esm server.js"

To run this command, you need to use common npm run start

Create our Server JavaScript File and our Server!

Then we need to create our server.js file and add this small code to run our server

import express from "express"
const app = express(),
port = process.env.PORT || 1024
app.get("/", (req, res) => {
res.send("Monster Cookie!"
})
app.get("/delete_monster", (req, res) => {
res.send("Monster Deleted")
})
app.listen(port, () => console.log(`http://127.0.0.1:${port}`))
Example adding the basi code to run our server
Example adding the basi code to run our server

For now, we have just two routes, the home page and the delete_monster.

Cookies Time!

Overall, we need to install the cookie-parser middleware, thus we can use in our side from the server field

npm i cookie-parser

Then we need to create our secretCookie code to encrypt our cookie before sending to the client, that is why you need to create a JSON file called credentials.development.json

Example creating json file with our secret cookie
Example creating json file with our secret cookie

Inside, we will create a simple JSON with secretCookie string

{
"secretCookie": "This is your secret code"
}
Example secretCookie string object
Example secretCookie string object

After that we need to create a conf.js file and with this file created can export the credential for our cookie parser middleware

const key         = process.env.NODE_ENV || "development",
credentials = require(`./.credentials.${key}`)
module.exports = { credentials }
Example importing the secretCookie and exporting
Example importing the secretCookie and exporting

Then we need to call it in our server file and passing as a variable to our cookieParser middleware

Example calling credentials secretCookie
Example calling credentials secretCookie

Then we will bake some cookies and send it to the client with res.cookie() method and clear all the cookies with the clearCookie() method

import express          from "express"
import cookieParser from "cookie-parser"
import { credentials } from "./conf"
const app = express(),
port = process.env.PORT || 1024
app.use( cookieParser( credentials.secretCookie ))
app.get( "/", ( req, res ) => {
res.cookie( "monster_cookie", "Yummy Yummy" ).send( "Monster Cookie!" )})
app.get( "/monster_signed", ( req, res ) => {
res
.cookie( "monster_cookie_signed", "Chop chop", {
signed: true,
})
.send( "Monster Cookie Signed!" )
})
app.get( "/delete_monster", ( req, res ) => {
res
.clearCookie( 'monster_cookie_signed' )
.clearCookie( 'monster_cookie' )
.send( "Monster Deleted" )})
app.listen( port, () => console.log( `http://127.0.0.1:${ port }` ))
Example creating cookies and send them to the client
Example creating cookies and send them to the client

Then when we run our server we have this

Example server running and browser view
Example server running and browser view

But what happened with our cookies?

You can do two ways, download an extension for chrome or open the Chrome DevTools

Example Chrome DevTools
Example Chrome DevTools

Extension for Google Chrome editThisCookie

Example extension for Google Chrome
Example extension for Google Chrome

It looks that we have our cookie, let’s go to the monster_signed URL to get our two cookies

Example cookies on the browser
Example cookies on the browser

Great then if you see the signed cookie has more information or encrypted data this is because of our cookieParser middleware and the secret cookie also this signed cookie takes precedence

Then delete our cookie with the delete_monster URL to clear our cookies

Example delete our cookies
Example delete our cookies

As you see, I deleted the cookies with the URL with the clearCookie()

Sessions

Install express-session to add session with cookies, the best way to maintain the state of our project

npm i express-session

And adding the middleware to our server.js file

app.use( expressSession({
resave: true,
saveUninitialized: false,
secret: credentials.secretCookie
}))
Example adding the expressSession middleware to our server file
Example adding the expressSession middleware to our server file

With this configuration, resave is to save back to the store, saveUninitialized setting to true make to save uninitialized session to the store, secret is to sign the session ID cookie.

Using sessions

To use sessions, you need to create a userName and add a string, but how we can do that?

The session is created inside our request object, and we can add properties to the session object like userName

Example adding session to our server
Example adding session to our server

If you see we add a session userName and colorScheme so far, let’s see in action, running our server we will have something like below

Example output on the console about session
Example output on the console about session

The session scheme is not defined and the userName called Anonymous an instance of the session property, and we have the cookie object with some important properties.

To delete, we can use delete operator and save null to the userName property.

Clearing the userName and adding to null
Clearing the userName and adding to null

Conclusion

With this we can add cookies delete them and create session with express-session library this is fascinating because we can also make it secret, useful and encrypted.

Sources

--

--

Rodrigo Figueroa
Geek Culture

I’m a Web Developer, fanatic of books and Smash Player.