Kickstarting your Node application — RESTful APIs, Authentication, Security — PART 1

Souvik Majumder
Geek Culture
Published in
6 min readJul 25, 2021
Source: Unsplash

So you own a grocery food chain and on one fine day, an idea pops up in your mind about creating a website which will be more of a dashboard in order for you to manage your products and sales. You have your initial front-end designed and developed using a framework of your choice, let’s say React, Vue or Angular. It’s now time to come up with the backend. After a little bit of comparison and research, you decided to use Node.js for developing the backend application. So what are key ingredients that you need ?

I am gonna discuss and explain the following in this article:-

PART -1

  • Setting up the basic structure or boilerplate of your application
  • Developing RESTful APIs

PART -2

  • Authenticating and Authorizing your service requests
  • Enabling Security against various vulnerabilities.

Let’s start cooking !!!

Structuring the Boilerplate

While there is no specific or official way to design the structure of your application, I normally follow a systematic and an easy way myself. But before we do so, let’s first create our node project.

  • Install NodeJS in your local machine, open VS Code or any other editor of your choice, choose a folder, open a terminal and run npm init to initialize the node project.
  • Give a name in your package.json file and the other optional details.
  • Install express npm package, by running npm install — save express.
  • Create an index.js file.

Before I structure the boiler plate, let’s use express to create API endpoints in index.js file itself.

I need to install nodemon npm package too, for the server to watch and identify changes made in files and automatically restart itself again.

Run the command

npm install — save nodemon

Open package.json and include a start script

Execute npm run start to Start the Node Server

Open browser and hit the URL http://localhost:8080/

Let’s create one more GET Endpoint.

And one POST Endpoint too.

So, we have all the end points present in this single index.js file.

Now it’s time to structure the boiler plate, so that we can segregate the endpoints accordingly for the ease of development.

Just consider the scenario where you go to a restaurant, you give your order to the waiter. The waiter (routes) takes your order and gives it to the head chef (controller). The head chef passes on the order to the cook (service). The cook takes out the vegetables or meat from the refrigerator (model), cooks with all other ingredients and his amazing cooking skills. He then gives the prepared dish back to the head chef who then passes on the same to your waiter. The waiter (route) now comes to you with the dish and you get to enjoy the delicious meal.

Route — > Controller — > Service — > Model — > Database

Create folders for routes, services, controllers and models.

Let’s say we want APIs related to products, sales and employees.

First of all, inside the routes folder, we create 3 separate files for products, sales and employees, along with an index.js file which will combine the code from all the above 3 files.

Now open the products.js file and include the below two lines.

So, we are using the Router class of express.

Now move the code of getProducts and createProduct that we created earlier inside the main index.js, to here. Replace all ‘app’ to ‘router’.

Export the router at the end of the product.js file

Open index.js inside routes folder and initialize the express module and it’s Router class.

Import the route exported from product.js

All the APIs related to products should be identified by another endpoint named ‘product’ appended before the particular API name.

Export the router at the end of the index.js file

Go back to the original main index.js file and import the route that was combined in the router/index.js from all the other files.

Use this ‘routes’ with an ‘api’ appended in the path.

Save and check the browser

Repeat this same procedure for sales and employees.

routes/employees.js

routes/sales.js

routes/index.js

Now, let’s bring the corresponding controllers also in the picture.

Inside the controllers folder, create 3 controllers for products, employees and sales with the name product.js, employees.js and sales.js respectively.

Open controllers/product.js and create 2 functions ‘getProducts’ and ‘createProduct’.

Move the code chunk for the sample responses that we had written inside the routes/product.js file as shown below. Export both the functions at the end.

In routes/product.js, import the controller/product.js and call the functions accordingly as shown below.

Rerun the API in the browser to check the response.

So the link App — > Router — > Controller is established. Repeat the same procedure for Employees and Sales.

controllers/employees.js

routes/employees.js

controllers/sales.js

routes/sales.js

Now, let’s bring Services also to the picture.

Inside the services folder, create 3 services for products, employees and sales with the name product.js, employees.js and sales.js respectively.

Open services/product.js and similar to what we did earlier, create two functions named ‘getProducts’ and ‘createProduct’. However in this case, the functions will not access the request parameters directly.

Rather, in the controller/product.js file itself, we will grab what all we need from the request query parameters (if any) and pass those as functional parameters to the functions belonging to service/product.js.

In this case, since we are fetching all the products, so there is nothing to pass in the parameters.

services/product.js

In controller/product.js, we import the services/product.js file and call the function accordingly that returns the data. We then send the returned data from the function as a response to the route.

To ensure that the response is sent only after receiving the data, we make both the functions in services/product.js and controllers/product.js asynchronous

Had it been for a single product, then we might have needed to pass the product id.

services/product.js

Thus, the link App — > Router — > Controller — > Service is now established.

Repeat the same exercise for Employees and Sales too.

And we’re done from the API creation part.

Now we have all our APIs ready. We can consume these easily in our front-end app.

Wait !!!

Don’t you think it’s openly accessible to anyone ? I mean you can definitely deploy your Node.js application to a cloud but does it ask for any kind of user credentials before you can access the data coming through the API ? No right ? That means any human being on this planet will be able to see your crucial data if they get the deployed URL somehow, without having the need to provide any sort of credentials.

A Big Risk !!!!!! Don’t worry, I got your back :) Let’s move on to the next part to see how we can authenticate our APIs.

Go to PART 2

--

--

Souvik Majumder
Geek Culture

Full Stack Developer | Machine Learning | AI | NLP | AWS | SAP