NextRequest wont let me set status code
Answered
Small Münsterländer posted this in #help-forum
Small MünsterländerOP
I just switched to App Routing and use NextResponse.
Even though the doc explains it like the following it wont let me
second param can only be a response init. I dont know how to set the response code withing a NextResponse. For a normal response it works
Even though the doc explains it like the following it wont let me
return NextResponse.json({ token }, { status: 200 })second param can only be a response init. I dont know how to set the response code withing a NextResponse. For a normal response it works
Answered by riský
You shouldnt need to use NextResponse.json anymore, the
Response.json should work fine7 Replies
Black carp
That looks right for the app router, can you give more context? is it in a route.ts/js and a GET/POST etc?
Small MünsterländerOP
The route.ts looks like this currently in the path src/app/api/login/route.ts
import {NextRequest, NextResponse} from 'next/server'
import {authenticateUser, generateToken} from '@/services/authService'
// Handle POST request
export async function POST(req: NextRequest) {
try {
const { username, password } = await req.json()
const user = await authenticateUser(username, password)
const token = generateToken(user.id)
return NextResponse.json({ token }) // Status code 200
} catch (error) {
if (!(error instanceof Error)) {
return NextResponse.json({ error: "Unknown Server error" })
}
return NextResponse.json({ error: error.message }) // Status code 401
}
}
// Handle GET request (if needed)
export async function GET(req: NextRequest) {
throw new Error('Invalid credentials')
// Implement logic for GET requests, if necessary
return NextResponse.json({ message: "GET method not implemented" })
}i can also confirm that i can reach the POST endpoint so the routing seems to work (not the GET endpoint tho but thats another topic)
this is when i try to add a status
Small MünsterländerOP
Ok little update: So apparently it works codewise. The response code seems to change. Just the Webstorm/Typescript cannot handle this?
You shouldnt need to use NextResponse.json anymore, the
Response.json should work fineAnswer
Small MünsterländerOP
ah i went along with what gpt suggested and since it mate a difference between pages and router i thought i need it. Thanks 🙂 ill go for the normal response then