Skip to content

API Protection #68

@brandonw504

Description

@brandonw504

Protect the API using an API key (stored in the Authorization header) that clients store in their environment variables. Since it is a little bit risky to store the API key on the client, we'll also be checking that the requests originate from only our own domains. You can check for these from the request that gets passed into the context for startServerAndCreateNextHandler. I'm not completely sure what is involved in making sure that someone can't spoof our domain name, but I will take a look and make sure that this structure works with that.

const handler = startServerAndCreateNextHandler(server, {
  context: async (req: NextRequest) => {
    const authHeader = req.headers.get('Authorization') || '';
    const apiKey = authHeader.replace('Bearer ', '');
    
    if (apiKey !== process.env.API_KEY) {
      throw new Error('Unauthorized: Invalid API key');
    }
    
    const origin = req.headers.get('Origin') || '';
    const referer = req.headers.get('Referer') || '';
    
    const isLocalDevelopment = process.env.NODE_ENV === 'development';
    const hasValidOrigin = ALLOWED_ORIGINS.includes(origin) || ALLOWED_ORIGINS.some(domain => referer.startsWith(domain));
    
    if (!hasValidOrigin && !isLocalDevelopment) {
      throw new Error('Unauthorized: Invalid origin');
    }
  }
});

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions