Yago Marinho
Back to the articles
  • ExpressJS
  • NodeJS
  • Auth

Improving security: adding an access key and rate limiting to a Node.js API with Express

I used environment variables and express-rate-limit to harden my Node.js API — and the result was a backend that's much easier to keep running.

Photo of Yago MarinhoBy: Yago MarinhoLast updated on:
In a world where more than 35% of web traffic comes from malicious bots, protecting an application, even a simple one, is essential. In this article, I share how I implemented two small but important security improvements in my Notion Blog project, using an access key stored in an environment variable and a rate limiter with Express.

Table of Contents

💡
You can check out the full project in the project repository

Implementing the API Access Key

The access key was the first step toward strengthening the security layer.
It works like an “entry badge”: every request to the API has to present a valid token in the Authorization header.
If the token is missing or wrong, the request is rejected with a 401 (unauthorized) status.
The check is simple but effective: the server compares the token it receives with the value set in the API_ACCESS_TOKEN environment variable.
This is a simplified access key implementation, meant only to make sure that just the intended users and applications can reach the content the API serves.
const apiKeyAuthorization = Middleware( request => async (): Promise<any> => { const auth = request.headers.authorization if (!auth) return Response({ status: 401, body: { message: 'API Access Token is missing' }, }) const [, token] = auth.split(' ') if (!token) return Response({ status: 401, body: { message: 'API Access Token is missing' }, }) if (token !== process.env.API_ACCESS_TOKEN) return Response({ status: 401, body: { message: 'API Access Token is invalid' }, }) return Next({ request }) }, ) // route definitions export const routes: Route[] = [ Route({ path: '/posts', handler: handlerPipe(apiKeyAuthorization, getPostListHandler), env: { covers }, }), Route({ path: '/post/:slug', handler: handlerPipe(apiKeyAuthorization, getPostDataHandler), env: { covers, posts }, }), Route({ method: 'post', path: '/posts/webhooks/notion', handler: handlerPipe(verifySignatureMiddleware, triggerWebhookHandler), env: { timer }, }), ]
This strategy ensures that only whoever holds the right key — usually the application's own frontend — can interact with the API.
Simple as it is, it blocks anonymous access and helps prevent resources from being consumed improperly.

Keeping things secure in Next.js

Since the project's frontend is built with Next.js, I made sure the access token would never be exposed in the client (frontend) code bundle.
To do that, every function that consumes the API was implemented with the server-only directive, which ensures the code runs exclusively on the Next.js backend, and without the NEXT_PUBLIC prefix.
That way, the token stays protected on the server and is never included in the JavaScript bundle that reaches the browser.
This small decision eliminates the risk of leaking credentials by accident and strengthens the isolation between client and server.
Here are the Next.js app services using the access key to authorize access. Keep in mind that the service functions only run on the backend.
import "server-only" // NextJS only export async function getPostList() { const headers = new Headers() headers.set('Authorization', bearer(process.env.API_ACCESS_TOKEN!)) const result = await fetch(`${config.api.baseUrl}/posts`, { cache: 'force-cache', headers, }) let posts: Cover[] = [] if (result.ok) posts = await result.json() return posts }
This strategy is simple, but it opens the door to improving and moving the application forward. Looking ahead, we could think about a module for creating parameterized API keys, which would make the application even more secure and scalable.

Implementing the Rate Limiter

The second security improvement was request rate control, also known as rate limiting.
It's there to prevent abuse, like automated scripts that hit the API hundreds of times in a few seconds.
Using the ‘express-rate-limit’ library, this middleware makes the implementation really easy: you just set a few basic parameters and you're done
import { rateLimit } from 'express-rate-limit' app.use(limiter()) function limiter() { return rateLimit({ windowMs: 60 * 1000, // a 1-minute window limit: 5, // only 5 calls per minute per IP standardHeaders: true, legacyHeaders: false, handler: (_, response) => { // returning a JSON response to make it easier to consume response.status(429).json({ status: 'error', message: 'To many requests. Please try again later', }) }, }) }
I set a time window of one minute and capped the number of requests at five per IP within that window.
When the limit is reached, the server responds with a 429 (Too Many Requests) status and a message telling the user to try again later.
This implementation is lightweight, straightforward and adds an extra layer of protection without hurting the application's performance.

Roadmap and next steps

  • Improve the design to reflect a more modern and consistent blog.
  • Add performance monitoring scripts for the content.
  • Use a bundler to optimize the application's size within the monorepo.
  • Refactor the code to decouple modules and prepare the application for future replacements without major impact.

Conclusion

These small improvements — the access key and the rate limiter — brought a significant security gain to the project.
More than protecting endpoints, they show a responsible engineering mindset, where concern for security and good practices grows along with the application.
In the end, what really matters is what these decisions communicate:
that there's care, intention and maturity in building every part of the system.
To me, this is the kind of detail that turns simple code into a professional project — and shows any professional that security and quality aren't optional; they're principles.
💡
You can check out the full project in the project repository
Photo of Yago Marinho
Yago MarinhoSenior Software Engineer. I build AI-powered products, from design to deploy.
See portfolio ↗