Back to Templates

Protecting express routes with permissions

Prevent unauthorized access to routes using RBAC

Written by
chronark
Framework
Express
Language
Typescript
Prevent unauthorized access to routes using RBAC

Express with middleware permissions

Protecting your routes
unkey.dev

Quickstart

Create a permission and role

  1. Go to app/authorization/permissions and click on the "Create New Permission" button.
  2. Enter call-protected-route as the name and add a description if you want.
  3. Click "Create New Permission"
  4. Now head over to /app/authorization/roles and click on the "Create New Role" button.
  5. Enter a name for the role, for example, admin and select the permission from the prevous step
  6. Click "Create".

Create your API

  1. Go to https://unkey.dev/app/apis and click on the "Create New API" button.
  2. Give it a name.
  3. Click "Create".

Create your first key

  1. Click "Create Key" in the top right corner.
  2. Click "Create"
  3. Copy the key and save it somewhere safe.

Connect the key to the role

  1. Go to /app/apis and click on the API you created.
  2. Click on "Keys" in the tabs.
  3. Click on the key you created.
  4. Click on "Permissions" in the tabs.
  5. Check the role's checkbox to give the key the role and permission.

Set up the example

  1. Clone the repository
1 git clone git@github.com:unkeyed/examples.git
2 cd examples/express-with-middleware-permissions
  1. Install the dependencies
1 pnpm install
  1. Create a .env file and add the following:
1 UNKEY_ROOT_KEY=your-root-key
2 UNKEY_API_ID=your-api-id
  1. Start the server
1 pnpm dev
  1. curl the unprotected route
1 curl http://localhost:3000/public

It should return Hello world!

  1. curl the protected route
1 curl http://localhost:3000/protected -H "Authorization: Bearer <YOUR_KEY>"

It should return Hello protected world!

Protect your API.
Start today.

2500 verifications and 100K successful rate‑limited requests per month. No CC required.