Getting Data From MongoDB & Creating an API Key ValidationMiddleware in Express

Getting Data From MongoDB & Creating an API Key ValidationMiddleware in ExpressPankaj PanigrahiBlockedUnblockFollowFollowingJan 9This article is the 5th in the article series which will help you grasp different concepts behind Node.

js, and will empower you to create production ready applications.

This article expects the reader to know Babel and how to set it up.

Please read this article if you need to know how.

In this article we will learn to get data from the Mongo database using the official Node.

js driver, MongoDB.

First install the driver.

npm install mongodb –saveNow, according to the official documentation, this is how we connect to an instance:In every route, we can now connect to the DB and fetch the data.

But that method will be inefficient.

For the route we would have to open a connection, and then close it.

It would make our API slow.

Learning from the last article, let’s write a middleware function which will give us the DB connection in the request object.

Let’s use the same project as last time, and edit the app.

js file.

Put this code at the top part of the file:Here we’re importing the Mongo Client and setting the database connection to a global variable mongoClient.

Then inject a middleware function to modify the request object to have the DB instance.


use((req,res,next)=>{ req.

db = mongoClient.

db('test'); next();})We need to close the DB connection when our API stops.

Add this code at the bottom:Our app.

js looks like this:Create a file UserService.

js inside a folder services.

Write the below code in the file.

Here we export a function getUserDetails, which takes two parameters db and username and returns a promise with the user record matching the user name.

Now we’ll modify our old routes/user.

js file to the below code.

In the route method, we pass the DB instance and user name to the service method, and then we set the user details in the response data.

We have the following record in our DB.

Let’s run our code and hit the API using Postman.

We’ll try to retrieve the shown data from MongoDB in the API response.

Congrats !.We’ve just made our first API that fetches data from MongoDB.

Now we’ll add client API key validation middleware to our express API.

Why do we need such middleware?.In a real word project, we might have 50–60 APIs performing different tasks.

But every API might need some common functionalities, such as client API key validation, authentication check, user role validation etc.

In this tutorial we will see how to add client API key validation.

This will ensure our API can be called by the people who’ve been given a unique API key.

This also helps with throttling the number of requests coming from a client and creating analytics of the API hits for a particular client.

First, create another service file ClientService.

js in the services folder and write the following code:It is similar to the getUserDetails method we wrote earlier.

It searches for a client record with the matching API key and returns a promise.

Create a file authUtils.

js inside thecommon folder.

Import thegetClientDetails method here.

import {getClientDetails} from '.

/services/ClientService';Create a middleware function as shown.

This function takes three parameters: req, res, next.

export const clientApiKeyValidation = async (req,res,next) => { let clientApiKey = req.

get('api_key');}We get the header api_key using the req.

get() method given by express.

Let’s add a validation for the missing api_key.

Even if res.

send() ends the stream, we write return res.

send() to avoid any further code execution .

if(!clientApiKey){ return res.


send({ status:false, response:"Missing Api Key" });}Now once we have the api_key passed in the header, we will call the getClientDetails method imported earlier.

If we try to get the clientDetails — on a successful query, we allow the flow to go ahead by invoking next(), otherwise we stop the API flow and send the invalid API key response.

Our common/authUtils.

js file should look like:Now, inject this middleware to our express object.

Open the app.

js file and import the above method.

import {clientApiKeyValidation} from '.

/common/authUtils';Inject the method after the Mongo Client instance we did previously, as we need the Mongo instance.


use((req,res,next)=>{ req.

db = mongoClient.

db('test'); next();});app.

use(clientApiKeyValidation);Run the code and hit the API without any api_key.

We got the missing validation responseTry to hit the API with an incorrect API key.

And finally with the right API key:This is how we write our custom middleware methods.

This is a very powerful tool while building APIs in express.

We can do authorisation checks and create a response handler using the same method.

I hope you liked the article!.In the next article we’ll see how to implement authentication using Redis and a custom authorization module.


com/pankaj805/medium-05_mongo_clientIf you liked the article, please leave a comment and share it with others.


. More details

Leave a Reply