docs / articles / Node.js API Key Authentication Example

Node.js API Key Authentication Example

Sara Jul 09, 2026 2026-07-09 04:40:45

In the realm of web development, API keys play a pivotal role in authenticating and authorizing requests to your server. Node.js, with its robust ecosystem and non-blocking, event-driven architecture, is an excellent choice for building APIs. Today, we'll explore a practical example of implementing API key authentication in a Node.js application using the Express.js framework and the jsonwebtoken library.

Environment Variables in Node.js
Environment Variables in Node.js

Before we dive into the code, let's understand why API key authentication is crucial. It helps protect your API from unauthorized access, rate limiting, and abuse. By implementing API key authentication, you can ensure that only authenticated and authorized clients can access your API endpoints.

Ever needed to expose an endpoint to an external system but didn’t want to set up a full identity system? | Milan Jovanović
Ever needed to expose an endpoint to an external system but didn’t want to set up a full identity system? | Milan Jovanović

Setting Up the Project

To get started, we'll initialize a new Node.js project and install the required dependencies.

a man in a blue hoodie is smiling and has the words user ruth on it
a man in a blue hoodie is smiling and has the words user ruth on it

First, initialize a new Node.js project by running `npm init` in your terminal. Then, install the necessary packages: express, jsonwebtoken, and dotenv.

Installing Dependencies

Node.JS Cheatsheet
Node.JS Cheatsheet

Run the following command to install the required packages:

npm install express jsonwebtoken dotenv

Dotenv is used to load environment variables from a .env file into process.env.

Creating a .env File

an image of a computer screen with some text on it
an image of a computer screen with some text on it

Create a .env file in your project root and add your API secret key:

API_SECRET=your_secret_key_here

Now that we have our project set up and dependencies installed, let's move on to implementing API key authentication.

Implementing API Key Authentication

Session, JWT, Token, SSO, OAuth 2.0
Session, JWT, Token, SSO, OAuth 2.0

In this section, we'll create a middleware function to handle API key authentication using JSON Web Tokens (JWT).

First, import the required modules and load the API secret key from the .env file:

First AI Agent in Node.js
First AI Agent in Node.js
Implementing API Key Authentication in ASP.NET Core
Implementing API Key Authentication in ASP.NET Core
Tokens vs API keys
Tokens vs API keys
Build a Login and Logout API using Express.js (Node.js)
Build a Login and Logout API using Express.js (Node.js)
JWT Access Token vs Refresh Token Explained (Complete Guide)
JWT Access Token vs Refresh Token Explained (Complete Guide)
Add Watermark To Image In NodeJS
Add Watermark To Image In NodeJS
How to Get an OpenAI API Key
How to Get an OpenAI API Key
How to Set Up and Use Agent GPT
How to Set Up and Use Agent GPT
How to Create an OpenAI Secret API Key for ChatGPT or DALL E 2
How to Create an OpenAI Secret API Key for ChatGPT or DALL E 2
Top 6 Use Cases of Node.js Framework
Top 6 Use Cases of Node.js Framework
Node-Red Function Node for Beginners
Node-Red Function Node for Beginners
How to set up Node JS with Express and Welcome to Express - EcomSpark
How to set up Node JS with Express and Welcome to Express - EcomSpark
Open source luxury version ChatGPT 'YakGPT' that works only with a browser, voice input is also possible at a higher speed than the official UI
Open source luxury version ChatGPT 'YakGPT' that works only with a browser, voice input is also possible at a higher speed than the official UI
the hello, prodicodee shopping cart is shown in black and white text
the hello, prodicodee shopping cart is shown in black and white text
The Top 5 Node.js Linters
The Top 5 Node.js Linters
Random Password Generator JS - Code Snippet
Random Password Generator JS - Code Snippet
How to send spoof emails from domains that have SPF and DKIM protections? – Information Security Newspaper | Hacking News
How to send spoof emails from domains that have SPF and DKIM protections? – Information Security Newspaper | Hacking News
Javascript Closure tutorial ( Closures Explained )
Javascript Closure tutorial ( Closures Explained )
‘Accountsd Wants To Use the Login Keychain Virus’: Key Tips
‘Accountsd Wants To Use the Login Keychain Virus’: Key Tips
Passkey technology is elegant, but it’s most definitely not usable security
Passkey technology is elegant, but it’s most definitely not usable security

const express = require('express');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');

dotenv.config();
const app = express();
const API_SECRET = process.env.API_SECRET;

Creating the Authentication Middleware

Now, let's create the middleware function that will verify the API key (JWT) in the request header:

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (token == null) return res.sendStatus(401);

  jwt.verify(token, API_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);

    req.user = user;
    next();
  });
}

This middleware function extracts the token from the Authorization header, verifies it using the API secret key, and adds the decoded user object to the request for further use in your routes.

Protecting Routes with the Middleware

Now that we have our authentication middleware, we can use it to protect our API routes:

app.get('/protected-route', authenticateToken, (req, res) => {
  res.json({ message: 'Access granted to protected route.' });
});

In this example, only authenticated requests with a valid API key (JWT) will be able to access the '/protected-route' endpoint.

Generating API Keys (JWT)

To generate API keys (JWT), you can create a simple route that accepts a username and password, validates the credentials, and returns a JWT:

User Registration and Login

First, let's create a simple user model and a route for user registration:

const users = [{ username: 'admin', password: 'password' }];

app.post('/register', (req, res) => {
  const { username, password } = req.body;

  if (!users.some(user => user.username === username)) {
    users.push({ username, password });
    res.status(201).json({ message: 'User created successfully.' });
  } else {
    res.status(400).json({ message: 'Username already exists.' });
  }
});

Next, create a login route that generates a JWT upon successful authentication:

app.post('/login', (req, res) => {
  const { username, password } = req.body;

  const user = users.find(user => user.username === username && user.password === password);

  if (user) {
    const token = jwt.sign({ username: user.username }, API_SECRET, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid credentials.' });
  }
});

With these routes, users can register and log in to obtain a JWT, which they can use to authenticate their requests to your protected API endpoints.

In conclusion, implementing API key authentication in a Node.js application using Express.js and jsonwebtoken is a straightforward process. By following the example provided in this article, you can secure your API and ensure that only authorized clients can access your endpoints. Happy coding!