Accessing Data from Cookies and Forms using Express & Node.js
By: Joycee Catamora
Tags: Nodejs, JavaScript, Web Development, Expressjs, Programming

For the developers that have an interest in using node as a webserver or using WebSockets with Express. This article will surely be beneficial to you.

Express.js, or simply Express, is a back end web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js. — Wikipedia.org

Initial Setup

Create a package.json file for the application using the npm init command, to learn more about the specifications of NPM’s package.json you can go to this link otherwise press enter to keep the default configurations.

npm init

2. Install Express and add it to the dependency list by running the command below:

npm install express -- save

3. Install Nodemon, it is a utility that would monitor the changes you make in your source files and will automatically restart the server for you. This is helpful during the development so you don’t need to keep on restarting the server whenever you add some changes.

npm install nodemon -- save

4. Install Helmet — it is an Express middleware web framework. Helmet can help to secure Express applications from various known vulnerabilities by providing HTTP headers appropriately. Helmet is composed of 11 smaller middleware functions that set security-related HTTP request headers.

npm install helmet -- save

5. To be able to get information from cookies you will need to install a cookie parser. Cookie-parser is an Express middleware function responsible for parsing cookie header and will expose the cookie data as response.cookie.

npm install cookie-parser -- save

6. For your templates, you will need to install EJS. EJS is a simple templating language that will let you generate an HTML markup with plain Javascript.

npm install ejs -- save

7. Add index.js file in the root directory. This file is the same file you have specified as an entry point when generating a package.json.

touch index.js

8. Configuring package.json. In case you want to change the filename you’ve specified as an entry point in the package.json. You can specify it under the scripts section. And to be able to use Nodemon when running the application, you will need to change the property of the start command to:

“start”: “nodemon index.js”

Directory Structure

Express is an unopinionated web framework hence, the folder structure will not merely affect how the application runs as long as you provide the correct path to the scripts. In this project, since it’s just a simple application that will depict how to access data from form and cookies, we will use the folder structure below but if you want a detailed and complete scaffolding you may want to use Express generator instead.

.

├── public

│ └── stylesheets

│ └── styles.css

├── views

│ ├── login.ejs

│ └── welcome.ejs

├── index.js

├── package.json

└── README.md

Inside the main file

Now that you have finished setting up your application, we will start adding the scripts needed inside the index.js file. We will go through the codes line by line and I will try to add a detailed explanation of what the code does and what is it for.

The code below shows how to assign express in a constant and declared another constant app so we can envoke Express later.

const express = require(‘express’);

const app = express();

Then you have to specify the port you’ll be using, the port should be 1000 and above in order for it to work.

const port = 3000;

app.listen(port);

Express has a built-in middleware function that you need to add to specify the location of your static files — path. Since it is built-in you may notice that we didn’t need to install it during the initial setup. Just store it in a variable to be able to use it.

const path = require(‘path’);

It’s also customary and a standard to add the middleware Helmet for a secure connection.

const helmet = require(‘helmet’);

app.use(helmet());

You have to invoke express.json() — it is a built-it middleware function in Express that parses incoming requests with JSON payloads and is based on body-parser.

app.use(express.json());

And the express.urlencoded() — this parses urlencoded bodies and only look at requests where the Content-Type matches the Type option.

app.use(express.urlencoded());

For us to add and use static files inside the application, we will need to use Express built-in middleware — express.static(), it accepts the root argument which is the folder name from which you will be placing all of the static assets. In this application, we will put them inside the public folder.

If the file is not found, instead of displaying a 404 response it will then execute the next() argument in the callback then move to the next middleware to execute, allowing for fall-backs and stacking.

app.use(express.static(‘public’));

And then we need to define which javascript template to use, there are other JS templates available such as pug, handlebars, and mustache. However, in this application, we will be using EJS.

app.use(‘view engine’, ‘ejs’);

app.use(‘views’, path.join(__dirname, ‘views’));

On the root page, you will for now just display the ‘sanity check’ text. To make sure that our configuration and the codes that we have written are working fine. We will focus on the login page so no need to render detailed information on this page.

app.get(‘/’, (response, request, next) => {

app.send(‘Sanity check’);

});

We’re now done with the initial setup, you can try running this to your local machine with the command below:

npm start

Then navigate to https://localhost:3000 in your browser. You should be able to see the same page as to the screenshot below:

View to the root page.

Building the Form template

The focus of this article is to guide you on how to get data from the Form and Cookie so don’t waste too much time designing the template you can refer to the CSS I wrote in this file and copy it to your styles.css inside /public/stylesheet folders.

For the template, you need to create a new file login.ejs then place it inside /views folder and add these codes:

login.ejs page template.

In order for us to see the template above on the browser, we have to create a get request like so:

index.js — adding get a request to display the login.ejs page.

Great, now you can navigate to the browser and go to the login page. https://localhost:3000/login.

login page view.

Getting the data from cookie

If you go back and check the login form we created above, you will see that under the action property of the form tag we added a /process_login path that will exercise the codes we put inside the POST request. Follow the image below:

index.js — post method to get data from the form and to save that inside a cookie.

When you press the login button on the page, the username and password you have provided in the form will then be forwarded to the request body.

And we can use that to validate if we either redirect the user to a welcome page or back to the login page.

In the code above, to save those data to a cookie we just need to add:

response.cookie('username', username);

To make sure it’s working, inspect the page and navigate to the Application tab and click cookies on the sidebar:

Checking the data saved inside Cookies.

Once your user credentials matched the ones inside the userdetails object, you will be redirected to the welcome page:

Welcome page view — https://localhost:3000/welcome:.

Deleting data from Cookies

It’s very simple to delete the data saved inside the cookie. You will just need to add this code below.

response.clearCookie('username');

The last part is to add the code snippet for the logout.

index.js — logout GET method.

If you’re keen to learn and you want to get a complete copy of this application, you can clone this repository in my GitHub account. ✌🏻😉

Do you find this article helpful? Don’t forget to leave some feedback in the comment section.

References:

Express

Helmet

Specifications of NPM’s package.json