NextJS 13 API Routes: Better Than Expected!

Josh tried coding
31 Mar 202315:05

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

00:00

🚀 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.

05:02

🔍 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.

10:02

🎯 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

API stands for Application Programming Interface, which is a set of rules and protocols that allows different software applications to communicate with each other. In the context of the video, the focus is on how Next.js 13.2 introduces changes to its API handling, which is central to the theme of the video as it discusses the new API route handlers and their benefits over the old ones.

💡Next.js

Next.js is a popular React framework for building user interfaces. It is mentioned in the script as the platform that has introduced new API route handlers in version 13.2. The video discusses the evolution of API routes in Next.js, highlighting the improvements and changes in the way developers can handle API requests and responses.

💡API Route Handlers

API Route Handlers are functions in Next.js that handle incoming HTTP requests for a specific route. The video script discusses the transition from the old API routes to the new API route handlers, emphasizing the syntactical and paradigm shifts in how developers declare and manage API endpoints within the 'app' directory.

💡App Directory

The App Directory is a new feature in Next.js 13.2 that allows for a different structure and organization of the application's code. The script mentions that the new API route handlers are only available in this directory, indicating a shift in the recommended way to structure applications in Next.js.

💡HTTP Methods

HTTP Methods are the set of request methods predefined by HTTP/1.1, such as GET, POST, PUT, and DELETE, which specify the ways in which a request can be made. The video explains how each HTTP method can be handled by exporting a function with the corresponding name in the new API route handlers.

💡Request Body

The request body is the part of an HTTP request that contains the data sent to the server. The script discusses the changes in accessing the request body content in the new API route handlers, where developers now use `req.json()` instead of directly accessing `req.body` as in the old API routes.

💡Response

In the context of HTTP and APIs, a response is the answer that a server sends back to the client after processing a request. The video script illustrates the changes in how responses are sent back in the new API route handlers, with a focus on the new syntax and capabilities, such as easier JSON response handling.

💡Cookies

Cookies are small pieces of data stored on a user's computer by their web browser. The script explains how the new API route handlers in Next.js 13.2 have improved the way cookies are accessed, providing a cleaner syntax and more type-safe access compared to the old API routes.

💡Headers

Headers in HTTP are part of the request and response messages, containing additional information about the message. The video script discusses the improved access to request headers in the new API route handlers, allowing for a more straightforward and type-safe way to retrieve header values.

💡Redirection

Redirection in web development is the process of sending a user from one URL to another. The script highlights the new API route handlers' ability to easily perform redirections, showcasing a simple and clean syntax for redirecting requests to different URLs.

💡Streaming

Streaming refers to the process of sending data over a network in a continuous flow, allowing for real-time data processing. The video script discusses how the new API route handlers in Next.js 13.2 have streamlined the process of creating streamed responses, which can be particularly useful for real-time applications like chatbots.

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

play00:00

listen when they introduced the new API

play00:02

rods in nexjs 13.2 I didn't like him I

play00:06

was like why did they do it this is

play00:07

totally unnecessary the syntax is

play00:09

different how the hell do I get access

play00:11

to the request body content

play00:13

how are they better why'd they do it

play00:15

right in this video we're going to take

play00:17

a look at the new API World handlers in

play00:19

the app directory how are they better

play00:21

and what changed let's get a really good

play00:23

understanding for the new API World

play00:25

handlers how they work and how they

play00:27

compare to the old ones because there

play00:29

are some differences and I think the new

play00:31

ones are doing some stuff way better

play00:33

than the old ones ever could first off

play00:36

the API routes that you know from Nexus

play00:39

12 have been replaced with new API route

play00:42

handlers as Nexus 13.2 calls them

play00:45

essentially

play00:46

these are only available in the app

play00:49

directory if you opt in to use that

play00:51

which is not recommended for production

play00:53

yet however you totally can use that in

play00:55

that directory the way you initialize a

play00:58

new API Rod is by going into the API

play01:00

folder you can see here on the left hand

play01:02

side and then creating a new folder of

play01:04

what the API path should be called right

play01:07

so this would be slash API slash hello

play01:10

and then the route.ts is just for

play01:12

declaring the routes and does not count

play01:14

towards the API path so that wouldn't be

play01:17

slash route right it would just be slash

play01:19

API hello

play01:21

and then for each HTTP method we can

play01:24

export a function that has the

play01:25

corresponding name right so if we wanted

play01:28

to make a get request we would export a

play01:30

function called get if we wanted to make

play01:32

a post request and write the code to

play01:34

handle that post request for this API

play01:36

rotender the way we do that is by

play01:39

initializing a function that is called

play01:41

post and then any post request we make

play01:44

the slash API slash hello would be

play01:46

handled by that post request

play01:49

now there are some differences between

play01:51

these API routes between the old ones

play01:54

and the new ones syntactically but also

play01:56

in the Paradigm that you used to use

play01:58

them so what I want to show you is a

play02:01

little comparison first off of how the

play02:03

old ones compare to the new ones I think

play02:05

that makes a lot of sense so let's go

play02:07

into the app directory create a new

play02:09

folder called pages

play02:11

and inside of here we are going to

play02:13

create a new folder called API and that

play02:16

should go into source and not app so we

play02:18

have the app and the Pages directory at

play02:21

the same level and then the old way you

play02:24

used to declare an API route was under

play02:26

Pages slash API and then you would

play02:28

create a file with whatever the API Rod

play02:30

would actually be called so for example

play02:32

let's call this example Dot

play02:35

dot TS and then in here you'd declare

play02:39

the API Rod by saying const example or

play02:43

you usually just call this Handler the

play02:45

naming really doesn't matter

play02:47

it's going to be a function and we

play02:49

export that function as a default that's

play02:52

our API Handler right here and from

play02:54

next.js we get two parameters passed

play02:57

into this API road which is going to be

play02:59

the request of type next API request if

play03:02

you're working in typescript that's the

play03:04

types of your JavaScript you could just

play03:05

leave this whole thing out and then the

play03:07

response of type next API response and

play03:11

syntactically the new ones are way

play03:13

cleaner and let me show you why for

play03:15

example

play03:16

um the the only thing I think was easier

play03:19

in the old API roles was getting the

play03:21

body content in case of a for example

play03:23

post or patch request right you could

play03:25

just say cons body is equal to rectal

play03:28

body and we'd also want to import this

play03:30

type of course also from next and this

play03:32

is the way we get the body it's super

play03:33

simple right just rec.body and then we

play03:36

can access the body

play03:37

so for example let's just send back a

play03:40

rest dot status of 200 dot end and try

play03:43

making a request to the example API

play03:45

route I've already prepared a button to

play03:48

do that

play03:48

that makes a request to slash API and

play03:51

then do slash example let's make a post

play03:53

request so we get access to the body

play03:55

then as the request body we're going to

play03:57

send along a Json Dot stringify

play04:00

off let's just put an object in here

play04:02

saying hello

play04:04

and of type world right so let's start

play04:07

up the dev server and make a request to

play04:10

the old API wrote example.ts that we

play04:12

have just declared and also we want to

play04:15

log out the body just to see how we get

play04:18

access to that because that

play04:20

fundamentally changed in the new API

play04:22

rods there's a big difference in how we

play04:23

get access to the body content let's

play04:25

make a call and look into our console as

play04:27

to what happened and we can see the body

play04:29

content right here so all we need to do

play04:31

rack.body super simple if we try to do

play04:35

the same thing

play04:36

in the new API Rod let's have this side

play04:38

by side this on the left one is the new

play04:40

one on the right one is the old API rods

play04:42

let's make a post request to this route

play04:45

as well and then get access to the body

play04:47

content so we can say Khan's body is

play04:50

going to be equal to and we get access

play04:52

to the request object as well which is

play04:55

of type request by the way we don't need

play04:57

to import that type it's already built

play04:59

in it's a native browser API that's why

play05:01

we don't need to import it and then we

play05:03

can say rack.body right so just the

play05:06

exact same thing as with the old API

play05:09

route cones body is rect.body then let's

play05:11

log out the body

play05:13

and send back a new response I'm gonna

play05:16

get into the syntax differences here in

play05:18

the response in a second that just says

play05:20

okay and maybe you can guess what's

play05:22

about to happen maybe you can't let's

play05:24

change the button to the hello road so

play05:27

to the new API Rod this one right here

play05:29

and make the call again

play05:32

and now let's take a look at the body

play05:33

content

play05:34

oh what's that Josh you might ask the

play05:38

body is of type readable stream locked

play05:40

false State readable supports biop false

play05:44

that's super weird what the hell is that

play05:46

we don't want that right so the the way

play05:49

we access the body content has changed

play05:51

just a bit instead of doing rack.body we

play05:53

can do rec.json

play05:55

right and then convert that so when we

play05:58

make the call again let's see what

play06:00

happens

play06:01

okay and we still need to await that I

play06:04

was wondering why that happened we need

play06:06

to await the Json conversion because

play06:08

that's an asynchronous operation let's

play06:10

make the call again and now let's look

play06:11

into the console

play06:13

and as we can see the hello world object

play06:15

is right there so that's how we access

play06:17

the body content it's a bit different we

play06:19

need to await the rest or Json and then

play06:21

also you might have noticed that the way

play06:23

we send back responses has fundamentally

play06:26

changed in the new API rods here on the

play06:29

left side we just return a new response

play06:32

class and pass that a message and we can

play06:34

also if we wanted to pass it something

play06:36

like a status headers or a status text

play06:39

whereas with the old API rods we will do

play06:42

a rest dot status and then normally we'd

play06:45

have a DOT Json and in here we could

play06:49

pass whatever we wanted well if we

play06:51

wanted to send Json from the new API

play06:53

rods we would do that like this we could

play06:56

just do json.stringify

play06:58

and then send back an object of hello

play07:01

world just like we're requesting on the

play07:04

front end right so that's the syntax

play07:07

difference in the response right here

play07:08

and one thing that is way better in the

play07:11

new API rods is how we access the

play07:14

cookies and the headers it is way better

play07:18

so let's take a look at how we do that

play07:19

in the old Handler if you wanted to

play07:21

access the cookies we could say rack dot

play07:24

cookies right let's log them out console

play07:27

log rec.cookies in the old API route and

play07:31

let's make a request to the alt API rod

play07:33

with or button

play07:34

right let's make the call and now the

play07:36

cookies will be logged out to the

play07:38

console okay so we didn't pass any

play07:40

cookies to change that let's just create

play07:43

a cookie and then send that along the

play07:45

way we can do that

play07:46

is by going into the application tab

play07:48

under the dev tools and then let's cross

play07:51

just create a new cookie with a value of

play07:54

my cookie all right and then that will

play07:57

be sent Along on every request let's

play07:59

make the call again see what happens and

play08:01

now we can see the cookie my cookie but

play08:04

there's no easy way to access the

play08:06

cookies right so we could do something

play08:08

like that cookies and then dots and then

play08:11

cookie I guess if you're working in

play08:15

typescript that's not really cool right

play08:17

you you don't know if it exists and I

play08:19

think syntactically the new approach is

play08:22

cleaner so if we take a look at how we

play08:24

can access the cookie in the new API Rod

play08:26

that is rack dot cookie oh and by the

play08:29

way before we do that we can change the

play08:32

request to a next request that is what

play08:35

next slash server gives us as an

play08:37

extended type so we can easier handle

play08:39

this request so now we can say

play08:41

rec.cookies and then dot get and then

play08:44

here we can enter our cookie value so

play08:46

let's see what we call that we call it

play08:49

um just cookie so we could say

play08:51

rec.cookies.thead cookie

play08:54

and log that out right here so now let's

play08:57

make a request to the new API wrote

play08:59

Under slash hello

play09:01

let's enter it here go to our button

play09:03

make the request go back look into the

play09:06

console and it's undefined oh that's

play09:09

because I called it cookies and not

play09:11

cookie there we go let's make the call

play09:13

again look into our console now here we

play09:15

are name cookie value my cookie as you

play09:18

can see there's a name and the value

play09:20

property as compared to what we had in

play09:22

the old API world with just cookie my

play09:24

cookie I think the syntax is cleaner so

play09:27

for example we could access the name we

play09:29

could access the value in a types of way

play09:31

I think that makes a lot of sense and

play09:33

same goes for the headers right so there

play09:35

are multiple approaches to get the

play09:37

header I'm just going to show you the

play09:38

easiest one

play09:39

so we can just say in the same fashion

play09:42

as you got the cookies we can say

play09:44

rec.headers dot get and then just enter

play09:47

the name of the header for example the

play09:48

authorization header if that's what we

play09:51

wanted and then we could access the

play09:53

value

play09:55

or the name or whatever value

play09:57

um whatever header you want to access so

play10:00

I think syntactically this is pretty

play10:02

clean that's a big upgrade from the last

play10:04

API routes from the old ones what they

play10:06

have made super convenient in the new

play10:08

API Rod is redirecting the request so

play10:12

what we could do is if somebody made a

play10:14

let's get rid of a post for now let's

play10:16

just have the get request in here and if

play10:18

somebody made a get request to this API

play10:20

Rod we could redirect that request to

play10:22

anywhere we want and the way we do that

play10:24

is super simple we can do redirect

play10:28

import that from next slash navigation

play10:30

and literally just enter the URL that we

play10:33

want to redirect to for example this URL

play10:36

doesn't exist.com let's save that and

play10:40

next.js already knows because this is

play10:41

called unconditionally it will always

play10:44

happen it's kind of like a return right

play10:46

so this is unreachable code because we

play10:48

are returning with it redirect so let's

play10:51

make a request to our API route and

play10:53

verify that this redirect actually works

play10:55

so let's make a request so that API

play10:57

wrote a get request we can just use Curl

play10:59

for that to make a simple request and we

play11:02

are going to make a request to http

play11:04

localhost 3000 slash API slash hello or

play11:08

new API route let's press enter and what

play11:10

we expect to happen is to get back a 404

play11:13

because we we are redirecting to some

play11:15

random URL and that's exactly what we

play11:18

get Curl 404 this page could not be

play11:20

found great so whereas if we redirect to

play11:23

a domain that exists that we know exists

play11:26

for example localhost 3000 that will

play11:30

definitely exist because we are

play11:31

literally hosting that in the background

play11:33

we can make another call request and

play11:35

this time we will get back a 200

play11:37

response state is called 200 okay

play11:39

because that API Rod exists so by doing

play11:43

that we verified that the redirect works

play11:45

as we expected now one last example I

play11:48

want to cover is streaming if you wanted

play11:50

to do streaming in the old Nexus you

play11:52

would have to do the

play11:55

um The Edge runtime all right you would

play11:58

have to switch to the edge runtime

play12:00

meaning the syntax actually changed if

play12:03

you use the edge runtime by doing export

play12:06

const config is gonna be equal to an

play12:10

object and Export the runtime as expiry

play12:13

mental Dash Edge that means you opted in

play12:17

to the experimental Edge runtime meaning

play12:20

the way you send back responses also

play12:22

changed to the new syntax of the API

play12:25

rods instead of what we had previously

play12:27

and that allows you to do something

play12:29

called streaming a response and that has

play12:32

been streamlined no pun intended in the

play12:34

new API rods as well so I want to cover

play12:37

one example

play12:38

that they did in their documentation

play12:40

here where you create an iterator to

play12:43

stream function and then kind of mock a

play12:46

streamed response one example where that

play12:48

can come in handy for example would be

play12:50

an open AI API you can opt into

play12:53

streaming where you get back the chat

play12:55

gbt responses as you have the request

play13:00

open to the back end so let's copy that

play13:03

example in here we are creating an

play13:05

iterator to stream a timeout sleep that

play13:08

needs to be a number

play13:10

and then making a new text encoder and

play13:13

this essentially mocks the streaming

play13:16

right so we can get rid of the uh the

play13:19

old get request that we had save that

play13:21

and know what this code will do is it

play13:24

will mock a streaming response meaning

play13:26

every 200 milliseconds we are pretending

play13:29

to get back some HTML from a server

play13:33

um that we get back like this

play13:34

we're mocking a little delay and then we

play13:38

are putting that right here into the

play13:40

iterator that iterator can then be

play13:42

turned into a stream in the next line

play13:44

right here that we then send back to the

play13:47

client meaning we get back the response

play13:49

on the client as the server gets it

play13:51

meaning we get it in real time in the

play13:53

client if we put that in state and then

play13:54

display it right here the client would

play13:56

see something every 200 milliseconds

play13:58

instead of having to wait all the time

play14:00

for the entire API Rod answer to finish

play14:02

and then displaying it all at once

play14:04

making for a better user experience so I

play14:07

found that really cool the new syntax

play14:09

make that super simple and you can also

play14:12

switch between the runtimes in the new

play14:14

API rods if you're wondering how to do

play14:16

that you can export a const runtime

play14:20

and either that is node.js by default or

play14:23

you can also opt into something called

play14:25

Xperia mental Edge what I've just

play14:27

mentioned if that's what you want to do

play14:29

meaning your API rods will be closer to

play14:31

your end users with the trade-off being

play14:33

that you don't have access to all the

play14:35

apis there are because it's a different

play14:38

runtime right you don't have access to

play14:40

some apis that you have access to in the

play14:42

node.js environment and that's it that's

play14:44

the new API rods I like them honestly I

play14:47

didn't expect much of them at first I

play14:49

was really confused as to how to get

play14:51

access to the body content but now I

play14:53

actually enjoy working with them so

play14:55

that's going to be it for me thank you

play14:56

very much for watching

play14:57

and I wish you a lot of fun working with

play14:59

the new API routes if you build

play15:01

something cool let me know I'll see in

play15:02

the next one have a good one and bye bye

Rate This

5.0 / 5 (0 votes)

相关标签
Next.jsAPI HandlersWeb DevelopmentSyntax UpdateRequest BodyResponse HandlingCode ComparisonTypeScriptNode.jsEdge RuntimeStreaming API
您是否需要英文摘要?