Next.js Discord

Discord Forum

req.json() returns 500 when no JSON is sent

Answered
Allegheny mound ant posted this in #help-forum
Open in Discord
Allegheny mound antOP
I have the following route handler:

export async function POST(request: Request){
    // Line below throws 500 when no JSON is received
    const data = await request.json();

    if (!data) {
        return NextResponse.json({
            success: false,
            message: 'No data provided.'
        });
    }
}


Which works completely fine when the request includes JSON payload.

However, request.json() causes a 500 when the request does not include a JSON payload.

What's the solution here?
Answered by Giant panda
try/catch that case since you are naively trying to deserialize the stream without knowing for sure that it contains JSON.
View full answer

11 Replies

Giant panda
try/catch that case since you are naively trying to deserialize the stream without knowing for sure that it contains JSON.
Answer
@Giant panda try/catch that case since you are naively trying to deserialize the stream without knowing for sure that it contains JSON.
Allegheny mound antOP
I coulnd't figure out how to check wether any JSON got sent or not
At first I assumed request.json() would return null or {} if it didn't find anything
Giant panda
The server console will clearly show you that an error is being thrown in that case
So if your endpoint is designed to consume JSON then attempt to deserialize and let the catch handler deal with errors.
No need to validate the request body on top of it
@Giant panda The server console will clearly show you that an error is being thrown in that case
Allegheny mound antOP
Is this also valid? Seems to work:

    const contentType = request.headers.get('content-type');
    if (!contentType || !contentType.includes('application/json')) {
        return NextResponse.json({
            success: false,
            message: 'Invalid content type or no JSON sent.'
        });
    }
Giant panda
I am not sure, because the header could be set to JSON but the payload could be XML regardless. I don't know if Next somehow sanitizes this or validates the headers
¯_(ツ)_/¯