Starter Guides

API Key Middleware for Express

API Key Middleware for Express

API Key Middleware for Express

Saurabh Jain

Aug 23, 2024

API Key Verification in Express Apps

When building secure web applications, verifying API keys is crucial to ensure that only authorized users can access your services. The Oneloop Node.js SDK makes this process seamless by providing an easy-to-use middleware function that you can integrate into your Express applications.

Getting Started with Oneloop Middleware

To start using the Oneloop middleware in your Express app, you first need to install the Oneloop Node.js SDK. This SDK provides the tools necessary for interacting with Oneloop's API key verification service.

npm install @oneloop-hq/oneloop-ts

The Oneloop middleware is already defined in the Oneloop Node Express TypeScript Starter Kit. You can simply import this middleware into your project or copy the code directly from the repository.

Using Oneloop Middleware in Your Express App

Once you have the middleware in place, you can easily protect your routes by adding it to your Express application. The middleware has several key checks - valid, unexpired, not rate-limited, not usage-limited, permissions and more!

Here's how you can use it:

// Grab this key from the dashboard and define it as part of your environment
ONELOOP_KEY="KEY"

// No permissions to check
app.post("/profile", oneloopMiddleware([]), handler);

Or, if you need to verify specific scopes:

// Check that we read permissions of "profile" scope.
app.post(
  "/profile",
  oneloopMiddleware([{ id: "profile", read: true }]),
  readProfileHandler // defined by you
);

Conclusion

The Oneloop middleware simplifies API key verification in Express applications by leveraging the Oneloop Node.js SDK. By defining scopes and permissions, you can ensure that only authorized users have access to your API routes. This middleware not only enhances security but also makes it easy to manage API keys and their associated permissions. For a quick start, reference the Oneloop Node Express TypeScript Starter Kit, where the middleware is fully implemented and ready to use.

Saurabh Jain

Share this post