Protecting endpoints

In this guide, we'll cover how to secure your endpoint to ensure that it can only be accessed by NextCron. By setting up this added layer of security, you can feel confident that your endpoint will only be triggered by your NextCron jobs and prevent unauthorized access. In this example, we are going to demonstrate how to ensure that a NextJS route is only called by NextCron. Next, create a new API route in your Next.js app, for example pages/api/nextcron.js.

In this file, you can add the following code:

export default async function handler(req, res) {
  const { headers } = req;
  const apiKey = process.env.NEXTCRON_API_KEY;

  if (headers['x-nextcron-token'] !== apiKey) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // Handle your business logic here
  res.status(200).json({ OK: true });
}

In this code, we first extract the X-NextCron-Token header from the incoming request, and compare it to the API key stored in the NEXTCRON_API_KEY environment variable. If they don't match, we return a 401 Unauthorized response.

If the API key is valid, you can add your business logic.

Remember to set the NEXTCRON_API_KEY environment variable to the API key you received when you signed up for NextCron.

Last updated