0

I'm trying to follow the basic tutorial provided by NextJS to setup a middleware for my API. When trying to restrict origin (for testing purposes) to http://localhost:3000, the request.headers.get('origin') won't return anything, triggering my custom CORS error.

import {NextRequest, NextResponse} from "next/server";

const allowedOrigins = [
    'http://localhost:3000',
]

const corsOptions = {
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}


export function middleware(request: NextRequest) {

    const origin = request.headers.get('origin') ?? ''
    const isAllowedOrigin = allowedOrigins.includes(origin)

    // Handle simple requests
    const response = NextResponse.next()

    if (isAllowedOrigin) {
        response.headers.set('Access-Control-Allow-Origin', origin)
    } else {
        return Response.json({ message: 'CORS error' }, { status: 533 })
    }

    Object.entries(corsOptions).forEach(([key, value]) => {
        response.headers.set(key, value)
    })

    return response
}

export const config = {
    matcher: '/api/:path*',
}

When trying to log origin before verification, it shows a blank value. My frontend calls are simple fetch functions, nothing fancy here.

By logging the request, I can clearly see origin: 'http://localhost:3000'.

EDIT: after further testing, I noticed that it seems to be the case only with GET requests.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.