Nextbase Docs
Authentication

Login with API Key

Nextbase Ultimate supports authentication using API keys, which is useful for integrating with external services or for machine-to-machine communication.

Implementation

API key authentication is typically implemented using a third-party service like Unkey. The exact implementation details may vary based on your specific requirements and the service you're using.

Here's a general outline of how you might implement API key authentication:

  1. Generate an API key for the user or service that needs access.
  2. Store the API key securely (never in plain text).
  3. When a request comes in, validate the API key.
  4. If the key is valid, authenticate the request and proceed.

Usage Example

Here's a simplified example of how you might validate an API key in a Next.js API route:

import { NextApiRequest, NextApiResponse } from 'next';
import { verifyKey } from '@unkey/api';
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const apiKey = req.headers['x-api-key'] as string;
 
  if (!apiKey) {
    return res.status(401).json({ error: 'API key is required' });
  }
 
  const { result, error } = await verifyKey(apiKey);
 
  if (error || !result.valid) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
 
  // API key is valid, proceed with the request
  // ...
 
  res.status(200).json({ message: 'Authenticated successfully' });
}

Remember to handle API keys securely and follow best practices for API authentication.

On this page