generated from include-davis/Next.js-App-Router-Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
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