Starter Guides

How to add API Keys to NextJS Routes

How to add API Keys to NextJS Routes

How to add API Keys to NextJS Routes

Aahan Sawhney

Aug 7, 2024

Today we are going to explore how to add authentication to your public API endpoints built on NextJs

Background

NextJS has gained huge popularity over the past few years. It's features like Server Side Rendering (SSR), Static Site Generation, and built-in API support offer improved performance, advanced SEO optimization, and a great developer experience. With NextJS, you can define your frontend and backend code in a single repository.

Using Oneloop, you can quickly and easily add API keys to your NextJS routes. It's like Auth0, but for your API

Getting Started with NextJS App

The easiest way to get started is to using create-next-app. More info here

npx create-next-app

Install Oneloop NextJS SDK

Now we will install Oneloop NextJS SDK. This SDK wraps your functions and takes care of all the middleware and error handling. With this, you will be able to convert any of your endpoint route to an authenticated route, with a single line change

npm install @oneloop-hq/next


Adding API to your NextJS App

Once you are in your NextJS app, go to app/api folder and create 2 new directories /health and /profile. Each of there directories represents a valid endpoint. Now let's create route.js|ts under each of these new directories. These route files will contain our GET|POST|PATCH|DEL calls. Learn more about Route Handlers with NextJS

Add unauthenticated endpoint

Let us first start by testing our endpoints and make sure we can hit them successfully. Go to app/api/health/route.ts and add the following code

export const dynamic = "force-dynamic"; // defaults to auto
export async function GET(request: Request) {
  return new Response("Hello from the API", {
    headers: {
      "content-type": "text/plain",
    },
  });
}


Let's test this endpoint now by first running our app using npm run dev and then hitting this endpoint in our terminal

curl http://localhost:3000/api/health

This should give back a 200 with text Hello from the API


Add authenticated endpoint

Now let's do the same for our profile endpoint, but this time we will add authentication to it using Oneloop. The first step will be to signup for Oneloop account and generate your own SDK Keys. Learn more here

Once you have your Oneloop SDK Keys, let's add the code for our endpoint along with authentication

⚠Remember to replace YOUR_ONELOOP_SDK_KEY with your Oneloop SDK Key

import { useOneloop } from "@oneloop-hq/nextjs";

export const dynamic = "force-dynamic"; // defaults to auto

// eslint-disable-next-line
export const GET = useOneloop(
  async (request: Request) => {
    return new Response("Profile Endpoint Authenticated", {
      headers: {
        "content-type": "text/plain",
      },
    });
  },
  {sdkKey: "YOUR_ONELOOP_SDK_KEY"}
);


Testing our authenticated endpoint

Now let's first start by testing our endpoint without giving any authorization header

curl http://localhost:3000/api/profile

This should give you a 401 error saying {"error":"unauthorized"}

Now let's add our API Key and authenticate this endpoint. To generate an API Key, you can either use Oneloop Dashboard or use the following command below to get an API Key

💡Remember to replace YOUR_WORKSPACE_ID with your Oneloop Workspace ID. You can get this from your Oneloop Dashboard

curl -H 'Content-Type: application/json' \ -d '{ "name":"Test Key","workspaceId":"YOUR_WORKSPACE_ID", "customerID": "Test-Customer-ID", "scopes": [], "enabled": true }' \ -X POST \ https://api.oneloop.ai/v1/api-key

Now using the newly generated API Key, let's test our authenticated /profile endpoint again

curl -H 'Authorization: YOUR_API_KEY' \ https://api.oneloop.ai/v1/api-key

This should give you a 200 response saying Profile Endpoint Authenticated

Recap

So we just saw how we can add authenticated routes to our NextJS app with a few lines of code. You can get this entire code from our GitHub repository. There are more features that you get with Oneloop, like rate limiting, usage tracking, audit logs, and ip restrictions. But that is for another article

Happy building!

Aahan Sawhney

Share this post