NextJS 13 API Routes: Better Than Expected!
Summary
TLDRThis video script explores the new API route handlers introduced in Next.js 13.2, comparing them with the previous API routes. It delves into the syntax and paradigm shift, demonstrating how to access request body content, handle responses, and utilize improved cookie and header access in the new API handlers. The script also covers advanced features like redirecting requests and streaming responses, showcasing the streamlined and powerful capabilities of Next.js's latest update.
Takeaways
- 😀 Next.js 13.2 introduces new API route handlers, replacing the old API routes and offering a cleaner syntax and improved functionality.
- 🛠️ API route handlers are initialized in the 'app' directory and are only recommended for development, not production, at this stage.
- 📁 The new API route structure involves creating a folder for the API path and a file for each HTTP method, such as 'get' for GET requests and 'post' for POST requests.
- 🔄 There are syntactic and paradigm differences between the old and new API routes, with the new ones offering a more streamlined approach to handling requests.
- 📥 Accessing the request body in the new API routes has changed; instead of using `req.body`, you now use `await req.json()` to handle JSON payloads.
- 📊 The new API route handlers simplify sending responses, allowing for direct return of a new `Response` object with status, headers, and body.
- 🍪 Handling cookies and headers has been improved in the new API routes, providing a more intuitive and type-safe way to access and manipulate them.
- 🔄 Redirecting requests in the new API routes is straightforward, using the `redirect` function from `next/navigation` to easily direct clients to different URLs.
- 🚀 The new API routes support streaming responses, which can be beneficial for real-time data handling, such as chatbot interactions.
- 🔀 Switching between Node.js and Edge runtimes in the new API routes is possible, allowing developers to opt into the Edge runtime for closer proximity to end-users, albeit with some API limitations.
- 🎉 The presenter initially had reservations about the new API routes but found them to be enjoyable and efficient to work with after understanding their features and benefits.
Q & A
What is the main topic of the video?
-The video discusses the new API route handlers introduced in Next.js 13.2, their differences from the old API routes, and how they work.
Why were the new API route handlers introduced in Next.js 13.2?
-The new API route handlers were introduced to provide a cleaner syntax and improved functionality compared to the old API routes.
Where are the new API route handlers located in a Next.js project?
-The new API route handlers are located in the 'app' directory of a Next.js project.
How do you initialize a new API route in Next.js 13.2?
-You initialize a new API route by creating a folder in the 'api' directory within the 'app' folder, named after the API path, and then exporting functions for each HTTP method.
What is the difference in accessing the request body between the old and new API routes?
-In the old API routes, you could access the body directly with 'req.body'. In the new API routes, you need to use 'req.json()' and await the conversion of the body from a ReadableStream to a JSON object.
How have the ways to send back responses changed in the new API routes?
-In the new API routes, you return a new 'Response' class with the desired message and optionally status, headers, or status text. This is different from the old API routes where you used 'res.status' followed by 'res.json' or 'res.end'.
What is the improved way to access cookies in the new API routes?
-In the new API routes, you can access cookies using 'req.cookies.get('cookieName')', which provides a cleaner syntax and better type safety compared to the old API routes.
How can you access headers in the new API routes?
-You can access headers in the new API routes using 'req.headers.get('headerName')', which is a more straightforward and cleaner approach compared to the old API routes.
What is the new feature for redirecting requests in the new API routes?
-The new API routes allow for easy redirection of requests using the 'redirect' function from 'next/navigation', which simplifies the process of sending clients to different URLs.
How has streaming responses been streamlined in the new API routes?
-Streaming responses have been streamlined by allowing the creation of an iterator to stream function, which can be turned into a stream and sent back to the client, providing real-time data without waiting for the entire response.
Can you switch between different runtimes in the new API routes?
-Yes, you can switch between 'node.js' and 'experimental-edge' runtimes in the new API routes by exporting a 'runtime' constant with the desired value.
Outlines
🚀 Introduction to New API Route Handlers in Next.js 13.2
The video script introduces the new API route handlers in Next.js version 13.2, which replace the traditional API routes known from previous versions. The narrator initially expresses skepticism about the changes, particularly the altered syntax and the new method of accessing request body content. The script then outlines the process of setting up API route handlers within the 'app' directory, emphasizing the creation of a new folder for the API path and the exportation of functions named after HTTP methods to handle requests. The narrator promises a comparison between old and new API routes and an exploration of the advantages of the new system.
🔍 Comparing Old and New API Routes in Next.js
This paragraph delves into a detailed comparison between the old and new API routes in Next.js. It explains the process of declaring API routes in the 'pages' directory using the old method and contrasts it with the new approach in the 'app' directory. The narrator demonstrates how to access the request body in both the old and new API routes, highlighting the simplicity of the old method and the asynchronous nature of the new method, which requires the use of 'await'. The paragraph also discusses the changes in how responses are sent back, with the new API routes utilizing a 'Response' class and the old routes using a more straightforward status and end method. Additionally, it touches on the improved syntax for accessing cookies and headers in the new API route handlers.
🎯 Advanced Features of New API Route Handlers
The final paragraph of the script highlights advanced features of the new API route handlers in Next.js, such as the ability to redirect requests and stream responses. It showcases how easy it is to perform redirects with the new API by using the 'redirect' function from 'next/navigation'. The narrator also discusses the improved syntax for streaming responses, which allows for a more real-time experience on the client side, beneficial for applications like chatbots. The paragraph wraps up with a mention of the ability to switch between Node.js and Edge runtimes in the new API route handlers, providing flexibility depending on the use case. The narrator concludes by expressing a newfound appreciation for the new API route handlers and encourages viewers to share their experiences.
Mindmap
Keywords
💡API
💡Next.js
💡API Route Handlers
💡App Directory
💡HTTP Methods
💡Request Body
💡Response
💡Cookies
💡Headers
💡Redirection
💡Streaming
Highlights
Introduction of new API route handlers in Next.js 13.2 and their initial skepticism.
New API route handlers are only available in the app directory and are not recommended for production yet.
The process of initializing a new API route by creating a folder in the API folder and naming it after the API path.
Exporting functions for each HTTP method to handle requests for the new API route handlers.
Comparison between the syntax and paradigm of old and new API routes in Next.js.
Old API route declaration under Pages/Api with a file named after the API route.
New API route handlers provide cleaner syntax and a different approach to handling requests.
Accessing the body content in old API routes was simpler with `req.body`.
New API route handlers require using `req.json()` and awaiting the conversion for accessing the body content.
Differences in how responses are sent back in new API route handlers compared to the old ones.
Improved access to cookies and headers in new API route handlers with clearer syntax.
Demonstration of how to access cookies and headers in both old and new API route handlers.
New API route handlers make redirecting requests simpler with the `redirect` function.
Example of verifying the redirect functionality in new API route handlers using curl.
Streaming responses in new API route handlers, making it easier compared to the old method requiring Edge runtime.
Example of creating an iterator to stream function for simulating a streamed response.
Ability to switch between Node.js and Edge runtimes in new API route handlers.
Personal reflection on the initial confusion and eventual appreciation for the new API route handlers.
Invitation for viewers to share their creations using the new API route handlers.
Transcripts
listen when they introduced the new API
rods in nexjs 13.2 I didn't like him I
was like why did they do it this is
totally unnecessary the syntax is
different how the hell do I get access
to the request body content
how are they better why'd they do it
right in this video we're going to take
a look at the new API World handlers in
the app directory how are they better
and what changed let's get a really good
understanding for the new API World
handlers how they work and how they
compare to the old ones because there
are some differences and I think the new
ones are doing some stuff way better
than the old ones ever could first off
the API routes that you know from Nexus
12 have been replaced with new API route
handlers as Nexus 13.2 calls them
essentially
these are only available in the app
directory if you opt in to use that
which is not recommended for production
yet however you totally can use that in
that directory the way you initialize a
new API Rod is by going into the API
folder you can see here on the left hand
side and then creating a new folder of
what the API path should be called right
so this would be slash API slash hello
and then the route.ts is just for
declaring the routes and does not count
towards the API path so that wouldn't be
slash route right it would just be slash
API hello
and then for each HTTP method we can
export a function that has the
corresponding name right so if we wanted
to make a get request we would export a
function called get if we wanted to make
a post request and write the code to
handle that post request for this API
rotender the way we do that is by
initializing a function that is called
post and then any post request we make
the slash API slash hello would be
handled by that post request
now there are some differences between
these API routes between the old ones
and the new ones syntactically but also
in the Paradigm that you used to use
them so what I want to show you is a
little comparison first off of how the
old ones compare to the new ones I think
that makes a lot of sense so let's go
into the app directory create a new
folder called pages
and inside of here we are going to
create a new folder called API and that
should go into source and not app so we
have the app and the Pages directory at
the same level and then the old way you
used to declare an API route was under
Pages slash API and then you would
create a file with whatever the API Rod
would actually be called so for example
let's call this example Dot
dot TS and then in here you'd declare
the API Rod by saying const example or
you usually just call this Handler the
naming really doesn't matter
it's going to be a function and we
export that function as a default that's
our API Handler right here and from
next.js we get two parameters passed
into this API road which is going to be
the request of type next API request if
you're working in typescript that's the
types of your JavaScript you could just
leave this whole thing out and then the
response of type next API response and
syntactically the new ones are way
cleaner and let me show you why for
example
um the the only thing I think was easier
in the old API roles was getting the
body content in case of a for example
post or patch request right you could
just say cons body is equal to rectal
body and we'd also want to import this
type of course also from next and this
is the way we get the body it's super
simple right just rec.body and then we
can access the body
so for example let's just send back a
rest dot status of 200 dot end and try
making a request to the example API
route I've already prepared a button to
do that
that makes a request to slash API and
then do slash example let's make a post
request so we get access to the body
then as the request body we're going to
send along a Json Dot stringify
off let's just put an object in here
saying hello
and of type world right so let's start
up the dev server and make a request to
the old API wrote example.ts that we
have just declared and also we want to
log out the body just to see how we get
access to that because that
fundamentally changed in the new API
rods there's a big difference in how we
get access to the body content let's
make a call and look into our console as
to what happened and we can see the body
content right here so all we need to do
rack.body super simple if we try to do
the same thing
in the new API Rod let's have this side
by side this on the left one is the new
one on the right one is the old API rods
let's make a post request to this route
as well and then get access to the body
content so we can say Khan's body is
going to be equal to and we get access
to the request object as well which is
of type request by the way we don't need
to import that type it's already built
in it's a native browser API that's why
we don't need to import it and then we
can say rack.body right so just the
exact same thing as with the old API
route cones body is rect.body then let's
log out the body
and send back a new response I'm gonna
get into the syntax differences here in
the response in a second that just says
okay and maybe you can guess what's
about to happen maybe you can't let's
change the button to the hello road so
to the new API Rod this one right here
and make the call again
and now let's take a look at the body
content
oh what's that Josh you might ask the
body is of type readable stream locked
false State readable supports biop false
that's super weird what the hell is that
we don't want that right so the the way
we access the body content has changed
just a bit instead of doing rack.body we
can do rec.json
right and then convert that so when we
make the call again let's see what
happens
okay and we still need to await that I
was wondering why that happened we need
to await the Json conversion because
that's an asynchronous operation let's
make the call again and now let's look
into the console
and as we can see the hello world object
is right there so that's how we access
the body content it's a bit different we
need to await the rest or Json and then
also you might have noticed that the way
we send back responses has fundamentally
changed in the new API rods here on the
left side we just return a new response
class and pass that a message and we can
also if we wanted to pass it something
like a status headers or a status text
whereas with the old API rods we will do
a rest dot status and then normally we'd
have a DOT Json and in here we could
pass whatever we wanted well if we
wanted to send Json from the new API
rods we would do that like this we could
just do json.stringify
and then send back an object of hello
world just like we're requesting on the
front end right so that's the syntax
difference in the response right here
and one thing that is way better in the
new API rods is how we access the
cookies and the headers it is way better
so let's take a look at how we do that
in the old Handler if you wanted to
access the cookies we could say rack dot
cookies right let's log them out console
log rec.cookies in the old API route and
let's make a request to the alt API rod
with or button
right let's make the call and now the
cookies will be logged out to the
console okay so we didn't pass any
cookies to change that let's just create
a cookie and then send that along the
way we can do that
is by going into the application tab
under the dev tools and then let's cross
just create a new cookie with a value of
my cookie all right and then that will
be sent Along on every request let's
make the call again see what happens and
now we can see the cookie my cookie but
there's no easy way to access the
cookies right so we could do something
like that cookies and then dots and then
cookie I guess if you're working in
typescript that's not really cool right
you you don't know if it exists and I
think syntactically the new approach is
cleaner so if we take a look at how we
can access the cookie in the new API Rod
that is rack dot cookie oh and by the
way before we do that we can change the
request to a next request that is what
next slash server gives us as an
extended type so we can easier handle
this request so now we can say
rec.cookies and then dot get and then
here we can enter our cookie value so
let's see what we call that we call it
um just cookie so we could say
rec.cookies.thead cookie
and log that out right here so now let's
make a request to the new API wrote
Under slash hello
let's enter it here go to our button
make the request go back look into the
console and it's undefined oh that's
because I called it cookies and not
cookie there we go let's make the call
again look into our console now here we
are name cookie value my cookie as you
can see there's a name and the value
property as compared to what we had in
the old API world with just cookie my
cookie I think the syntax is cleaner so
for example we could access the name we
could access the value in a types of way
I think that makes a lot of sense and
same goes for the headers right so there
are multiple approaches to get the
header I'm just going to show you the
easiest one
so we can just say in the same fashion
as you got the cookies we can say
rec.headers dot get and then just enter
the name of the header for example the
authorization header if that's what we
wanted and then we could access the
value
or the name or whatever value
um whatever header you want to access so
I think syntactically this is pretty
clean that's a big upgrade from the last
API routes from the old ones what they
have made super convenient in the new
API Rod is redirecting the request so
what we could do is if somebody made a
let's get rid of a post for now let's
just have the get request in here and if
somebody made a get request to this API
Rod we could redirect that request to
anywhere we want and the way we do that
is super simple we can do redirect
import that from next slash navigation
and literally just enter the URL that we
want to redirect to for example this URL
doesn't exist.com let's save that and
next.js already knows because this is
called unconditionally it will always
happen it's kind of like a return right
so this is unreachable code because we
are returning with it redirect so let's
make a request to our API route and
verify that this redirect actually works
so let's make a request so that API
wrote a get request we can just use Curl
for that to make a simple request and we
are going to make a request to http
localhost 3000 slash API slash hello or
new API route let's press enter and what
we expect to happen is to get back a 404
because we we are redirecting to some
random URL and that's exactly what we
get Curl 404 this page could not be
found great so whereas if we redirect to
a domain that exists that we know exists
for example localhost 3000 that will
definitely exist because we are
literally hosting that in the background
we can make another call request and
this time we will get back a 200
response state is called 200 okay
because that API Rod exists so by doing
that we verified that the redirect works
as we expected now one last example I
want to cover is streaming if you wanted
to do streaming in the old Nexus you
would have to do the
um The Edge runtime all right you would
have to switch to the edge runtime
meaning the syntax actually changed if
you use the edge runtime by doing export
const config is gonna be equal to an
object and Export the runtime as expiry
mental Dash Edge that means you opted in
to the experimental Edge runtime meaning
the way you send back responses also
changed to the new syntax of the API
rods instead of what we had previously
and that allows you to do something
called streaming a response and that has
been streamlined no pun intended in the
new API rods as well so I want to cover
one example
that they did in their documentation
here where you create an iterator to
stream function and then kind of mock a
streamed response one example where that
can come in handy for example would be
an open AI API you can opt into
streaming where you get back the chat
gbt responses as you have the request
open to the back end so let's copy that
example in here we are creating an
iterator to stream a timeout sleep that
needs to be a number
and then making a new text encoder and
this essentially mocks the streaming
right so we can get rid of the uh the
old get request that we had save that
and know what this code will do is it
will mock a streaming response meaning
every 200 milliseconds we are pretending
to get back some HTML from a server
um that we get back like this
we're mocking a little delay and then we
are putting that right here into the
iterator that iterator can then be
turned into a stream in the next line
right here that we then send back to the
client meaning we get back the response
on the client as the server gets it
meaning we get it in real time in the
client if we put that in state and then
display it right here the client would
see something every 200 milliseconds
instead of having to wait all the time
for the entire API Rod answer to finish
and then displaying it all at once
making for a better user experience so I
found that really cool the new syntax
make that super simple and you can also
switch between the runtimes in the new
API rods if you're wondering how to do
that you can export a const runtime
and either that is node.js by default or
you can also opt into something called
Xperia mental Edge what I've just
mentioned if that's what you want to do
meaning your API rods will be closer to
your end users with the trade-off being
that you don't have access to all the
apis there are because it's a different
runtime right you don't have access to
some apis that you have access to in the
node.js environment and that's it that's
the new API rods I like them honestly I
didn't expect much of them at first I
was really confused as to how to get
access to the body content but now I
actually enjoy working with them so
that's going to be it for me thank you
very much for watching
and I wish you a lot of fun working with
the new API routes if you build
something cool let me know I'll see in
the next one have a good one and bye bye
Ver Más Videos Relacionados
Create A Python API in 12 Minutes
You are using useFetch WRONG! (I hope you don't)
Build an API SaaS using Next.js, Prisma, Stripe in under an hour (Get paid for your API)
API GATEWAY and Microservices Architecture | How API Gateway act as a Single Entry Point?
Flask AJAX Tutorial: Basic AJAX in Flask app | Flask casts
Creating a Web API Project
5.0 / 5 (0 votes)