Prerequisites

Creating an express server

1

Create express application

First run the following:

mkdir unkey-with-express
npm init -y
npm install cors dotenv express ts-node
npm install -D @types/cors @types/express ts-node-dev typescript

Then update your package.json to have the following

"scripts": {
    "start": "ts-node ./index.ts",
    "build": "tsc",
    "serve": "node dist/index.js"
  },
2

Install

Now install the @unkey/ratelimit package

npm install @unkey/ratelimit
3

Add Root Key to env

Add your root key to your .env file

UNKEY_ROOT_KEY="YOUR_KEY"
4

Creating the server

Create a file called server.ts and add the following code

server.ts
import express, { Request, Response, Application } from 'express';
import dotenv from 'dotenv';
import { Ratelimit } from '@unkey/ratelimit';
//For env File
dotenv.config();

const app: Application = express();
const port = process.env.PORT || 8000;

/**
This can be a seperate util for easy configurable ratelimiting across
multiple routes.

namespace = The route identifier you would like to ratelimit
limit = The amount of requests
duration = amount of time to limit against for example "30s"

**/
const limiter = new Ratelimit({
namespace: "express-example",
limit: 2,
duration: "30s",
rootKey: process.env.UNKEY_ROOT_KEY
});


app.get('/', (req: Request, res: Response) => {
  res.send('Welcome to Express & TypeScript Server');
});

// This endpoint is protected by Unkey
app.get('/secret', async (req: Request, res: Response) => {
  const identifier = req.getUserId() // or ip or anything else you want

  const ratelimit = await unkey.limit(identifier)
  if (!ratelimit.success){
    res.status(429).send("Please try again later")
  }

  return res.status(200).send("ok");
})
app.listen(port, () => {
  console.log(`Server is listening at http://localhost:${port}`);
});
5

Running the server

npm run start
6

Try it out

curl 'http://localhost:8000/secret'

You will need to curl a few times to see the ratelimiting error. Once you do, you, you will need to wait to perform the action again.

What is next?

Now that you’ve seen the power of Unkey, check out some resources below to continue your journey.

Was this page helpful?