Logo

dev-resources.site

for different kinds of informations.

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

Published at
11/5/2024
Categories
api
express
middleware
apikeys
Author
honest_will
Categories
4 categories in total
api
open
express
open
middleware
open
apikeys
open
Author
11 person written this
honest_will
open
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.
middleware Article's
30 articles in total
Favicon
I Really like Middleware in NodeJs/Express.
Favicon
CSRF tokens in Nextjs
Favicon
Create Your Own Middleware Application Using Chain of Responsibility
Favicon
Rust: Demystifying Middleware in Actix Web
Favicon
Apache Camel - The Integration Framework for Modern Applications
Favicon
Express.js Applications with Middleware
Favicon
Nostr: a Better Future for Authentication
Favicon
Building Secure, Scalable, and Low-Latency IoT Middleware
Favicon
How to Build Scalable Middleware with Express.js
Favicon
How to quickly add API Key validation to a Node Express API
Favicon
Middleware in Lithe: How It Works and How to Create Your Own
Favicon
Middleware no Lithe: Como Funciona e Como Criar o Seu Próprio
Favicon
🗺️ Peta Jalan Laravel: Menjelajah Routing, Middleware, dan Controller (Indonesian Version)
Favicon
Centralized Exception Handling in ASP.NET Core - Custom Middleware
Favicon
Adding Logging and Error Handling Middleware to Your Go API
Favicon
A Simple Way to Handle Locale-Specific URLs in Express
Favicon
Entendendo e Implementando Middlewares no Express.js
Favicon
Deep Dive ASP.NET Core Middleware : Part 1
Favicon
Next.js Middleware: Simple Guide to Control Requests
Favicon
Building a middleware with Nextjs
Favicon
Extending Prisma ORM with Custom Middleware: Logging, Validation, and Security
Favicon
Understanding NestJS Middleware
Favicon
Implementing Secure Authentication in Next.js with JWT and MongoDB. Protect Routes using middleware
Favicon
Middleware function Execution Problem and Solution
Favicon
Securing Next.js APIs with Middleware Using Environment Variables
Favicon
Middleware and Interceptors in NestJS: Best Practices
Favicon
NodeJS Security Middlewares
Favicon
Middleware to Asp.net Core MVC Application + Custom Middleware
Favicon
Implementing CORS in a Custom Next.js Server
Favicon
How to Set Up Signup, Login, and Logout using Django's Middleware

Featured ones: