DEV Community

Cover image for How to quickly add API Key validation to a Node Express API
honest will
honest will

Posted on

How to quickly add API Key validation to a Node Express API

In this example, we’ll create a simple middleware for Express using the excellent AuthAPI's key manager. The middleware will check every incoming request to ensure it has a valid API key.

First, head over to theauthapi to create your free account.

A short message from the BBC - "Other key managers are available".

In the AuthAPI dashboard, create a new project and an access token. Copy and store the project ID and access token somewhere secure and safe (don't commit to git!).

Let's generate a test API key using a CURL command. Copy this command and paste it into your favourite Terminal.

curl --location 'https://api.theauthapi.com/api-keys/' --header 'x-api-key: [YOUR ACCCESS TOKEN]' --header 'Content-Type: application/json' --data-raw '{
  "name": "Name your key!",
  "projectId": "[YOUR PROJECT ID]"
}'
Enter fullscreen mode Exit fullscreen mode

Now you can just switch over to your favourite code editor.

If you have Node installed and some experience with Express, you can just run this command in a new project folder. If you need a good starter on Node+Express, watch this thorough video from free code camp.

npm i theauthapi express --save

Now, create your server's app file; let's call it index.js for this example.

The following code checks the request for the header x-api-key, then validates it with theauthapi service. We're using Express's handy middleware override method app.use. You can explicitly name your override if you are using more than one in your app.

import TheAuthAPI from "theauthapi";
import express from "express";
const app = express();

const theAuthAPI = new TheAuthAPI.default("${accessKey}");

app.use(function (req, res, next) {
  if (req.headers["x-api-key"]) {
    theAuthAPI.apiKeys
      .authenticateKey(req.headers["x-api-key"])
      .then((key) => {
        if (!key) {
          res.status(401).send({ message: "Invalid API key" });
        }
        req.key = key;
        next();
      })
      .catch((err) => {
        res.status(500).send({ message: err.message });
      });
  } else {
    res.status(401).send({
      message: "No API key, be sure to set it as the 'x-api-key' header",
    });
  }
});

app.get("/", (req, res) => {
  res.send(req.key);
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

To start your server, run the command:

node index.js

The server will be up and running unless you get any error messages.

Now, you're ready to test your first validated request.

Testing some invalid requests

Let's test the app without a valid key to check the results:

curl --location 'localhost:3200'
Enter fullscreen mode Exit fullscreen mode

Let's try to send a request with an invalid key:

curl --location 'localhost:3200' \
--header 'x-api-key:madeupkeynametest'
Enter fullscreen mode Exit fullscreen mode

Finally, let's validate a real key!

Copy the API key generated in the first example and replace it in the command below.

curl --location 'localhost:3200' \
--header 'x-api-key:[COPIED API KEY]'
Enter fullscreen mode Exit fullscreen mode

How did you get on? Feel free to drop me a comment if you have a question.

Side notes
  • I prefer to use Postman to run requests for my localhost. But there are plenty of alternatives in the market, e.g. Insomnia, Hoppscotch, HTTPie, and Paw.
  • This is a straightforward example of how to add API key validation to your request. Go deeper; you can add rate limiting and expiries to keys very quickly. Check out what the AuthAPI can do.

Top comments (0)