how does the api folder works in newer versions? next version 14.2.1.
Answered
Mike posted this in #help-forum
MikeOP
How i can use the api folder in newer versions like 14.2.1. because with /pages/api it doesnt works
Answered by Northeast Congo Lion
55 Replies
@Mike How i can use the api folder in newer versions like 14.2.1. because with /pages/api it doesnt works
Northeast Congo Lion
/api/route_name/route.{js,ts}e.g if you have api route for say a contact form
/api/contact/route.jsinside here
const handler = async() => {
//API LOGIC HERE
}
export { handler as POST }and to submit to API url you would do
fetch(`/api/contact`, {
method: 'POST'
}Northeast Congo Lion
not
page.jsso
page.js is for /app/page_name/page.jsMikeOP
ahh route so sorry
Northeast Congo Lion
use
route.jsNortheast Congo Lion
inside
app folder please @Mikee.g
/app/api/... sorryjust drag it, restart terminal shud be ok
MikeOP
⨯ TypeError: res.status is not a function
const handler = async (req, res) => {
res.status(200).json({ name: 'John Doe' });
}; // Hier fehlte eine schließende Klammer
export { handler as GET };How i can send an response in newer versions?
Northeast Congo Lion
return NextResponse.json({
name: 'John Die'
},
{
status: 200
});try this
the second object is optional if u want to pass back http status code
MikeOP
okay
but why i cant do it with the old way like res.json ?
Northeast Congo Lion
because it's the
new way 🙂haha i dont know how to explain it sorry\
MikeOP
but that way is shit
😅
Northeast Congo Lion
lol feedback for the next team i guess
MikeOP
Yes, i dont like the new nextresponse
Northeast Congo Lion
you can do other ways
MikeOP
which one?
Northeast Congo Lion
best bet is reading the docs
i am sure there is couple approaches available
MikeOP
because i worked years with the normal way
okay, i will read it.
Northeast Congo Lion
well
it is still the default response
nextresponse is just extended to add some nice helpers
Northeast Congo Lion
Answer
MikeOP
thank you very much
it also work like this without nextresponse
Northeast Congo Lion
yep
Picardy Spaniel
Hi , how do I call that /app/api/test/route.ts on my server component, e.g. /app/profile/page.tsx
I tried using await fetch('/api/test') but it fails
Northeast Congo Lion
You can’t use relative url on server component
So /api/test won’t work
I believe u need full url
You can store url in .env
And use string interpolation to combine process.env.WEBSITE_URL & /api/test
@Picardy Spaniel
Picardy Spaniel
right, got that working now
now I am facing an unauthorized one, I'm using next-auth, even if my session is active
that api call for my http://localhost:3000/api/test returns the unauthorized
is there any particular config I need to include here
Northeast Congo Lion
Please create a new thread with your issue in detail
Share your next auth config
The api route code etc