5Kas
How to securely allow localhost to access through CORS, without exposing it to anyone’s localhost?
It is recommended to do this often in web apps:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// Define allowed origins
const allowedOrigins = [
'http://localhost:3000',
'http://localhost:3001',
'http://localhost:3002',
'http://localhost:3003',
'https://my.site',
]
export function middleware(request: NextRequest) {
// Get the origin from the request headers
const origin = request.headers.get('origin')
// If the origin is not in the allowed list, return null in the header
const corsOrigin =
origin && allowedOrigins.includes(origin)
? origin
: allowedOrigins[0]
// Handle OPTIONS preflight request
if (request.method === 'OPTIONS') {
return NextResponse.json(
{},
{
headers: {
'Access-Control-Allow-Origin': corsOrigin,
'Access-Control-Allow-Methods':
'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400',
},
},
)
}
// Handle the actual request
const response = NextResponse.next()
// Add CORS headers to the response
response.headers.set('Access-Control-Allow-Origin', corsOrigin)
response.headers.set(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS',
)
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization',
)
return response
}
// Configure which routes use this middleware
export const config = {
matcher: '/:path*',
}
Here, this is Next.js middleware which checks if you are on localhost, and allows any request to be made.
Isn't that very insecure? Or at least, a hacker could crawl your website and make API calls if they load it in Puppeteer or something and make HTTP/REST requests from "localhost". Puppeteer is a browser API in Node.js for web automation.
So if I were a hacker, I would create a web app, load it in localhost, and make a request from the frontend localhost to whatever backend API I want. Perhaps there is a simpler way to hack along these lines, but yeah.
How can I allow CORS for localhost (so I can test against a production API server), but only for me, not anyone else?