This tutorial is absolutely amazing for people who have no idea how api routes work (me). The way you go in depth explaining things is by far the best I've seen, you make it so easy to understand. Fantastic content!
Hi, I just wanted to say a big thank you. I've been searching across the internet to find the answer you just gave. It's only now I know you can create api routes in the backend (calling external apis) and then call the api routes in the frontend to grab that data. I would have never thought of that, if it wasn't for you. Thank you very much.
Thank you Dave for great content. I have one question though. Isn't it better to use below code for getting "id" in "Dynamic Api route" section of your video: export async function GET(request: Request, { params }: { params: { id: string } }) { const id= params.id; } Regards
I don't know if it is _better_ but it is another possibility. I have shown that way in previous videos in this series. Now you have an alternative, too! 🚀
Concerning when and when not to use the page routes . You said the page routes and the generateParams are built at the same and its not advisable to use it . but what if we want to acutallly protected some APi keys and that is why we are using the page routes at build time to fetch the data
Only a server component uses generate static params. Your API keys are protected in a server component. They stay on the server. No need for a server component to send a request to an API route. Just request the data you need from the server component.
@@DaveGrayTeachesCode wow the quickest response . And last one is the generateParams the only way to differentiate the ssr from ssg. I know we use the build to see it but would like to know other strict rule on knowing how to stick to either ssg or ssr
@@justiceessiel6123 If the server component just returns JSX and doesn't fetch data or other data retrieval operations, it will be static. If it does fetch data but doesn't use generateStaticParams, it will be SSR. If it does use generateStaticParams, it is usually a dynamic page using SSG.
@@DaveGrayTeachesCode please make a video on the topic of CURD with (Neon Serverless DB / Postgres DB and Next JS), it is really handy if you can make 2 videos, one CRUD operations with SQL Queries and 2nd one with any ORM like Prisma. It is humble request Please make it ASAP.
can I am creating a simple todo app, and I want to make the same nextjs server to serve a react native app using Route handlers to create Restful APIs to handle SQLite database for example ? and the concurrent requests, how the NextJS route handlers deal with concurrent requests ?
There is a much simpler way to get params from a dynamic route export async function GET( request: NextRequest, { params }: { params: ParamsType } ) { const { id } = params;
I have shown the params way in previous videos concerning dynamic routes if you've been following this series? I suppose I could or should have shown both. Not sure that one is easier / simpler than the other. Now you have an alternative. 😃
Great video, My web app is now using backend in node, so I can transfer all my backend to next js handlers? Or its not come to replace node backend service and just it's just helper?
It is not exactly the same as Node.js and Express. You will probably be interested in my next video on middleware later this week. I'd wait on switching over.
Thanks, sir! btw shouldn't we create PUT and DELETE functions inside the dynamic route rather than passing 'id' in the body? I think putting 'id' inside the body when using the DELETE operation instead of using a dynamic route is often discouraged but I am not sure.
I'm struggling to get my head around where to fetch data (content) from a CMS. I set it up with a Route Handler, and fetched it in a server component. Now after watching this I'm thinking I don't need the API. I use an environment variable(secret), but I understood that would still be secure without the API. Is that correct? You're a legend, Dave
That is correct. No need for the API route when you can fetch from the server component. Use the API routes for client components - processing forms, hiding URLs, hiding env keys, etc..
In the last section about the Dynamic API Route I missed the explanation to why we were doing that route. It would be nice if you could explain what or why we're doing what we are going to do next time :)
If we create the rest api using nextjs and after the build if we try to fetch the api after the build and we if update the data from the data base it won't fetch the updated data it reads from the cache how to over come that?
I've tried with version 13.4.2. I get an error message "SyntaxError: unexpected end of JSON input". Did someone get the same error message by using this version?
If this is in the DELETE route, I have filed an issue with Next.js: github.com/vercel/next.js/issues/48096 I see others are still having this issue. You can npm i next@13.2.4 to match what I think I have in my package.json for this video. You can check in the course resources.
You're welcome! It seems like you are asking about the database relationships when you ask about 1 to 1 and 1 to many. That is completely separate from API routes. You can connect to a database from your backend and request data - and that includes from your API routes as well as from your server components.
const todos : Todo[] = (await res).json(); This code gives the below error : Type 'Promise' is missing the following properties from type 'Todo[]': length, pop, push, concat, and 29 more.ts(2740) Had to make these changes to get the todos const response = await res; // Wait for the Promise to resolve const todos: Todo[] = await response.json(); // Wait for JSON parsing to complete
Remember, server components should not utilize these API routes. You can make the same requests directly in those. You could use these routes for client components.
Amazing video! I have a question and it might be silly. If I already created a react front end using react18 and I have a MongoDB. Can I use NEXTJS as the backend rest api for that react front end ? I was watching your node/express video this month but if I could use nextjs as the backend I think it would be an awesome way to get my head around nextjs. What do you think ?
great series man... one question - why do we mix up using Request type for the request and NextResponse type for the response? wouldn't it be better to stay consistent with one of them?
Hi Dave, can you plase show us how to deploy an express or next api to netlify with serverless function. This is something that I never find on TH-cam. I am sure its something many people struggle with. Thanks
I have a video on Serverless functions with Netlify here: th-cam.com/video/J7RKx8f4Frs/w-d-xo.html I will show how to deploy Next.js - including the REST API - later in this series.
Hi! I have a problem, maybe you will be able to help me. I have created react app using vite. While styling it, i have noticed that the size of each element is much bigger and overall elements are bigger. I have tried to deploy project and it looks awesome. Besides, if i go to responsive mode, it is also works as it should be. Hello from Ukraine🇺🇦🇺🇦🇺🇦, Thank you for your content, it inspires me to work harder.
Very interesting as always. Could you make a video about migration from React to Next?? If I have a MERN project, would the migration or mutation worth it??
Next.js is a React framework. Not much different there, but some things like routing are specific to Next.js. The backend has more differences from Node & Express, but I cover the basic set up here and middleware is the follow up to this video - coming soon.
Hy sir. I would like to ask this question should programmer be worrying about chatgpt AI. Replacing them ? In the future. I'm 15 and I'm new to the programming world but I'm seeing. People who don't even code. Using chatgpt AI to create. Apps and website. Without coding. . Should I focus on programming or just forget about it. Sorry for bad English 🙏
Great video like always! And the api routes would be even better if we could validate api incoming data with Zod and send back a complete array of errors!
13.4.4 still gives an error for DELETE handler: TypeError: Response body object should not be disturbed or locked at extractBody (node:internal/deps/undici/undici:6185:17) at new Request (node:internal/deps/undici/undici:7114:48) at new NextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/request.js:32:9) at NextRequestAdapter.fromNodeNextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:38:16) at NextRequestAdapter.fromBaseNextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:20:35) at RouteHandlerManager.handle (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/future/route-handler-managers/route-handler-manager.js:26:57) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async doRender (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/base-server.js:936:38) at async cacheEntry.responseCache.get.incrementalCache.incrementalCache (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/base-server.js:1162:28) at async /Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/response-cache/index.js:99:36 I had to downgrade to 13.2.4 adding some configurations to next.config.js: const nextConfig = { experimental: { appDir: true } }
We can get dynamic value of route same like we get for server component . ``` export const GET = async ( request: Request, { params: { id } }: { params: { id: string } } ) => { const res = await fetch(`${DATA_SOURCE_URL}/${id}`); const todo: Todo = await res.json(); if (!todo.id) return NextResponse.json({ message: "Todo not found" }); return NextResponse.json(todo); }; ```
Yes, you can. Go to the next video where I address this as it was mentioned in these comments before. If I don't show something in a video, that does not mean it cannot be achieved.
Thanks so much sir., Plese make video how to manage accessToken and refreshToken from express backend from your previous lesson th-cam.com/video/CvCiNeLnZ00/w-d-xo.html using nextauth in nextjs 13
This tutorial is absolutely amazing for people who have no idea how api routes work (me). The way you go in depth explaining things is by far the best I've seen, you make it so easy to understand. Fantastic content!
Glad it helped!
Dynamic Route can also been get like below
export async function GET ({ params }:{params:{id:string} }) {
const { id } = params
}
your teaching skills are immense Dave. you're one of the best in the business. always enjoying your series!
Glad you think so! 🙏
Hi, I just wanted to say a big thank you.
I've been searching across the internet to find the answer you just gave.
It's only now I know you can create api routes in the backend (calling external apis) and then call the api routes in the frontend to grab that data. I would have never thought of that, if it wasn't for you.
Thank you very much.
this is now my favorite teaching channel
Waiting for more from you sir. Hope u will teach Nextjs 13 in depth. Thanks a lot 🎉
Best next js tutorial in the youtube
Thank you!
i am forever grateful sir, been searching for a teacher that teaches next js
Thanks Dave, i finally get it to work.
at 29:47 I was getting a 500 error when I tried to send the request for todo id 199. deleting the JSON body resolved the error.
Thank you Dave for great content.
I have one question though. Isn't it better to use below code for getting "id" in "Dynamic Api route" section of your video:
export async function GET(request: Request, { params }: {
params: { id: string }
}) {
const id= params.id;
}
Regards
I don't know if it is _better_ but it is another possibility. I have shown that way in previous videos in this series. Now you have an alternative, too! 🚀
@@DaveGrayTeachesCode Thanks for the reply.
Thanks so much sir🙇. We love❤️ to practice and see more of this
Always welcome!
u make it easy to understand 😭thank youu
Great video - thank you!
Concerning when and when not to use the page routes . You said the page routes and the generateParams are built at the same and its not advisable to use it . but what if we want to acutallly protected some APi keys and that is why we are using the page routes at build time to fetch the data
Only a server component uses generate static params. Your API keys are protected in a server component. They stay on the server. No need for a server component to send a request to an API route. Just request the data you need from the server component.
@@DaveGrayTeachesCode wow the quickest response . And last one is the generateParams the only way to differentiate the ssr from ssg. I know we use the build to see it but would like to know other strict rule on knowing how to stick to either ssg or ssr
@@justiceessiel6123 If the server component just returns JSX and doesn't fetch data or other data retrieval operations, it will be static. If it does fetch data but doesn't use generateStaticParams, it will be SSR. If it does use generateStaticParams, it is usually a dynamic page using SSG.
@@DaveGrayTeachesCode you are the best ! Thank you sir
Killer video. Cant believe they still havent fixed the DELETE method!
Thank you and I agree!
Ok I got stuck here bc I kept getting an error. I was using Next 13.4.7
Thanks a lot for the series Sir!
Impressed with your teaching skills Dave, really impressive, please keep it up. I hope will learn a lot from you.
Thanks, will do!
@@DaveGrayTeachesCode please make a video on the topic of CURD with (Neon Serverless DB / Postgres DB and Next JS), it is really handy if you can make 2 videos, one CRUD operations with SQL Queries and 2nd one with any ORM like Prisma. It is humble request Please make it ASAP.
can I am creating a simple todo app, and I want to make the same nextjs server to serve a react native app using Route handlers to create Restful APIs to handle SQLite database for example ?
and the concurrent requests, how the NextJS route handlers deal with concurrent requests ?
There is a much simpler way to get params from a dynamic route
export async function GET(
request: NextRequest,
{ params }: { params: ParamsType }
) {
const { id } = params;
I have shown the params way in previous videos concerning dynamic routes if you've been following this series? I suppose I could or should have shown both. Not sure that one is easier / simpler than the other. Now you have an alternative. 😃
the strange thing is that its in the middle of the documentation 😭
hello, how to create api endpoint api/product and api/products without create separate folder, so those 2 endpoints are in same folder.
thanks
You could look at using a catch-all route: nextjs.org/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments
Very well teaching dave
Thank you!
Sir thank you 💕 you are really best for me
You're welcome!
Great video,
My web app is now using backend in node, so I can transfer all my backend to next js handlers?
Or its not come to replace node backend service and just it's just helper?
It is not exactly the same as Node.js and Express. You will probably be interested in my next video on middleware later this week. I'd wait on switching over.
Thanks, sir!
btw shouldn't we create PUT and DELETE functions inside the dynamic route rather than passing 'id' in the body? I think putting 'id' inside the body when using the DELETE operation instead of using a dynamic route is often discouraged but I am not sure.
You should be able to do either.
I'm struggling to get my head around where to fetch data (content) from a CMS. I set it up with a Route Handler, and fetched it in a server component. Now after watching this I'm thinking I don't need the API. I use an environment variable(secret), but I understood that would still be secure without the API. Is that correct? You're a legend, Dave
That is correct. No need for the API route when you can fetch from the server component. Use the API routes for client components - processing forms, hiding URLs, hiding env keys, etc..
Lookin forward to the middleware video 😊
Coming soon!
This was really helpful thanks.
Welcome!
Thank you so much Dave!
You're welcome!
is this not applicable in the latest next version? I tried DELETE method but can't received a message.
In the last section about the Dynamic API Route I missed the explanation to why we were doing that route. It would be nice if you could explain what or why we're doing what we are going to do next time :)
I suggest always cross-referencing the docs. I try to make it clear but I can't please everyone.
Sir is it possible to start side hustle using html and css
Yes, you could build websites with those.
Once this is setup, I can still use the same app folder for the front end part of right? and just use the API routes to fetch data and display on FE?
Note what I state in the video about fetching from app API routes - there are times you do not want to and times that you do.
@@DaveGrayTeachesCode Thanks for replying! I probably missed what you said haha. But I appreciate your tutorials nonetheless!
If we create the rest api using nextjs and after the build if we try to fetch the api after the build and we if update the data from the data base it won't fetch the updated data it reads from the cache how to over come that?
Keep going. The next lesson is all about revalidation.
very nice tutorial ❤
I've tried with version 13.4.2. I get an error message "SyntaxError: unexpected end of JSON input". Did someone get the same error message by using this version?
If this is in the DELETE route, I have filed an issue with Next.js: github.com/vercel/next.js/issues/48096
I see others are still having this issue.
You can npm i next@13.2.4 to match what I think I have in my package.json for this video. You can check in the course resources.
Very helpful tutorial thank you
You're welcome!
Hi, Thanks for your Tutorial, How can I use API Routes database to one to one and one to many ?
You're welcome! It seems like you are asking about the database relationships when you ask about 1 to 1 and 1 to many. That is completely separate from API routes. You can connect to a database from your backend and request data - and that includes from your API routes as well as from your server components.
quick question. i keep getting the url not found error each time. Is there something I am doing wrong?
It sounds like it. I don't know exactly what you're doing wrong but that should not be the result. You can see in the video I do not have that issue.
Hello sir.... whenever I try to connect to mongoDB via mongoose in app/api... it says topLevelAwait is not enabled...I cant understand why it says so
Are we not using the app directory anymore? Does this come down to preference or is there a use case for using either the src or app directory?
We _are_ using the app directory. Note that it is _inside_ the src directory. When you choose to use src, it is just a container for everything else.
@@DaveGrayTeachesCode Great, thank you!
const todos : Todo[] = (await res).json();
This code gives the below error :
Type 'Promise' is missing the following properties from type 'Todo[]': length, pop, push, concat, and 29 more.ts(2740)
Had to make these changes to get the todos
const response = await res; // Wait for the Promise to resolve
const todos: Todo[] = await response.json(); // Wait for JSON parsing to complete
can you make part of authentication
That will come _after_ this beginners series. Authentication is a more advanced topic.
This will be great, especially if it can also include roles, similar as the mern project we did, on teck notes app
Thank you, Dave
Welcome!
Thanks for sharing 👍
sir, the way of explain is awesome ! i liked to work like the way. would you please show the front end crud part using these funs if you have time.
Remember, server components should not utilize these API routes. You can make the same requests directly in those. You could use these routes for client components.
Amazing video! I have a question and it might be silly. If I already created a react front end using react18 and I have a MongoDB. Can I use NEXTJS as the backend rest api for that react front end ? I was watching your node/express video this month but if I could use nextjs as the backend I think it would be an awesome way to get my head around nextjs. What do you think ?
You could but I think it does have some limitations - at least currently - compared to using a traditional Node.js/Express backend.
Awesome explained
love it
Hi Sir,
What icon theme are you using?
I show my icons here: th-cam.com/users/shorts-uhzj-kjfV4
@@DaveGrayTeachesCode thanks
great series man...
one question - why do we mix up using Request type for the request and NextResponse type for the response? wouldn't it be better to stay consistent with one of them?
It is best to only use when needed. Look at this example from the docs: beta.nextjs.org/docs/routing/route-handlers#dynamic-route-handlers
Hi Dave, can you plase show us how to deploy an express or next api to netlify with serverless function. This is something that I never find on TH-cam. I am sure its something many people struggle with.
Thanks
I have a video on Serverless functions with Netlify here: th-cam.com/video/J7RKx8f4Frs/w-d-xo.html
I will show how to deploy Next.js - including the REST API - later in this series.
You are much more awesome 🎉
Thanks a lot!
You're welcome!
That was really great tutorial , if possible can you make tutorial on access and refresh token in next js .
I will cover auth at some time after this fundamentals series.
@@DaveGrayTeachesCode Ok 👍👍
Hi! I have a problem, maybe you will be able to help me. I have created react app using vite. While styling it, i have noticed that the size of each element is much bigger and overall elements are bigger. I have tried to deploy project and it looks awesome. Besides, if i go to responsive mode, it is also works as it should be. Hello from Ukraine🇺🇦🇺🇦🇺🇦, Thank you for your content, it inspires me to work harder.
This might be a good question to post in my Discord. Link in the description.
I have strong skill of html,css, tailwindcss and sass can start to earn money and continue my coding journey with my side hustle while learn coding. 💰
Yes, you could build websites with those.
Very interesting as always. Could you make a video about migration from React to Next?? If I have a MERN project, would the migration or mutation worth it??
Next.js is a React framework. Not much different there, but some things like routing are specific to Next.js. The backend has more differences from Node & Express, but I cover the basic set up here and middleware is the follow up to this video - coming soon.
why are you not using getServerSideProps ,
getStaticProps,
getStaticPaths in the whole tutorial ?
It's next@13.4.6 and they still haven't fixed the DELETE issue. 😭😭😭
update: with next@13.4.6 in development mode DELETE works fine with turbo...
I agree.
this is the wrong video title, It is supposed to be "How to connect with Rest API" not Build!!
Hy sir. I would like to ask this question should programmer be worrying about chatgpt AI. Replacing them ? In the future. I'm 15 and I'm new to the programming world but I'm seeing. People who don't even code. Using chatgpt AI to create. Apps and website. Without coding. . Should I focus on programming or just forget about it. Sorry for bad English 🙏
My answer to this frequently asked question: th-cam.com/users/shortsc8tUBvaAP1A
@@DaveGrayTeachesCodethanks ❤️🙏
Great video like always! And the api routes would be even better if we could validate api incoming data with Zod and send back a complete array of errors!
Agreed! That would make a good follow-up outside of this series.
Dave can you do a tutorial using next api with mongoose?
Yes, I can.
A REST Api with no route protection?
13.4.4 still gives an error for DELETE handler:
TypeError: Response body object should not be disturbed or locked
at extractBody (node:internal/deps/undici/undici:6185:17)
at new Request (node:internal/deps/undici/undici:7114:48)
at new NextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/request.js:32:9)
at NextRequestAdapter.fromNodeNextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:38:16)
at NextRequestAdapter.fromBaseNextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:20:35)
at RouteHandlerManager.handle (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/future/route-handler-managers/route-handler-manager.js:26:57)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async doRender (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/base-server.js:936:38)
at async cacheEntry.responseCache.get.incrementalCache.incrementalCache (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/base-server.js:1162:28)
at async /Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/response-cache/index.js:99:36
I had to downgrade to 13.2.4 adding some configurations to next.config.js:
const nextConfig = {
experimental: {
appDir: true
}
}
Yes, Next.js changes quickly. I recommend using the version of Next.js that I have in the package.json for each of these videos in this series.
We can get dynamic value of route same like we get for server component .
```
export const GET = async (
request: Request,
{ params: { id } }: { params: { id: string } }
) => {
const res = await fetch(`${DATA_SOURCE_URL}/${id}`);
const todo: Todo = await res.json();
if (!todo.id) return NextResponse.json({ message: "Todo not found" });
return NextResponse.json(todo);
};
```
Yes, you can. Go to the next video where I address this as it was mentioned in these comments before. If I don't show something in a video, that does not mean it cannot be achieved.
❤
Dave. I am a straight man but i want to marry you xD
😆🤣
Build api BEST bACKEND LANGUAGE JS IS MAKE TO FROONT DEV , IN Chile says pastry chef yo ypur cakes
Thanks so much sir.,
Plese make video how to manage accessToken and refreshToken from express backend from your previous lesson th-cam.com/video/CvCiNeLnZ00/w-d-xo.html using nextauth in nextjs 13
Auth is a more advanced topic that I plan to tackle sometime after this fundamentals course is complete. 🚀