How to Build a REST API with Next.js 13

Поделиться
HTML-код
  • Опубликовано: 18 сен 2024

Комментарии • 133

  • @minimumt3n204
    @minimumt3n204 Год назад +12

    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!

  • @tinymurky7329
    @tinymurky7329 10 месяцев назад +3

    Dynamic Route can also been get like below
    export async function GET ({ params }:{params:{id:string} }) {
    const { id } = params
    }

  • @andreaswu7973
    @andreaswu7973 Год назад +8

    your teaching skills are immense Dave. you're one of the best in the business. always enjoying your series!

  • @shaikhsanuar5339
    @shaikhsanuar5339 Год назад +3

    Waiting for more from you sir. Hope u will teach Nextjs 13 in depth. Thanks a lot 🎉

  • @akosbalint3485
    @akosbalint3485 Год назад +3

    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;

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +4

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

    • @h3nry_t122
      @h3nry_t122 Год назад

      the strange thing is that its in the middle of the documentation 😭

  • @web3compares
    @web3compares Год назад +2

    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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

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

    • @web3compares
      @web3compares Год назад

      @@DaveGrayTeachesCode Thanks for the reply.

  • @socialultra7219
    @socialultra7219 8 месяцев назад

    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.

  • @mdsalahuddin46464
    @mdsalahuddin46464 Год назад +1

    Best next js tutorial in the youtube

  • @monyourbae
    @monyourbae Год назад +2

    can you make part of authentication

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      That will come _after_ this beginners series. Authentication is a more advanced topic.

    • @PlayhouseMediaGroup
      @PlayhouseMediaGroup Год назад

      This will be great, especially if it can also include roles, similar as the mern project we did, on teck notes app

  • @zebrox4416
    @zebrox4416 Год назад +1

    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.

  • @onelastkiwi8041
    @onelastkiwi8041 7 месяцев назад

    this is now my favorite teaching channel

  • @saswatpranat6748
    @saswatpranat6748 Год назад +1

    Sir is it possible to start side hustle using html and css

  • @kynjal23
    @kynjal23 Год назад

    i am forever grateful sir, been searching for a teacher that teaches next js

  • @RhysLopez
    @RhysLopez 11 месяцев назад

    u make it easy to understand 😭thank youu

  • @davidjohn3740
    @davidjohn3740 Год назад

    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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

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

  • @AmodeusR
    @AmodeusR Год назад

    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 :)

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      I suggest always cross-referencing the docs. I try to make it clear but I can't please everyone.

  • @mywaycoding6413
    @mywaycoding6413 Год назад +1

    Sir thank you 💕 you are really best for me

  • @igbrowns1151
    @igbrowns1151 Год назад +1

    Thanks so much sir🙇. We love❤️ to practice and see more of this

  • @shazeemalichishty7322
    @shazeemalichishty7322 6 месяцев назад

    Thanks Dave, i finally get it to work.

  • @justiceessiel6123
    @justiceessiel6123 Год назад +1

    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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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.

    • @justiceessiel6123
      @justiceessiel6123 Год назад

      @@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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

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

    • @justiceessiel6123
      @justiceessiel6123 Год назад

      @@DaveGrayTeachesCode you are the best ! Thank you sir

  • @noahspottdev
    @noahspottdev 3 месяца назад

    Great video - thank you!

  • @k303k
    @k303k 9 месяцев назад

    Thanks a lot for the series Sir!

  • @shahabulalam8803
    @shahabulalam8803 Год назад

    Very well teaching dave

  • @juandaniel6726
    @juandaniel6726 Год назад

    Thank you so much Dave!

  • @LarryMarkel
    @LarryMarkel Год назад

    Killer video. Cant believe they still havent fixed the DELETE method!

  • @Jose_911
    @Jose_911 Год назад

    Awesome explained

  • @Sam_Pila
    @Sam_Pila 8 месяцев назад

    hello, how to create api endpoint api/product and api/products without create separate folder, so those 2 endpoints are in same folder.
    thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  8 месяцев назад

      You could look at using a catch-all route: nextjs.org/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments

  • @TravinskiyVladislav
    @TravinskiyVladislav Год назад

    Thank you, Dave

  • @amansinghbhadauria2818
    @amansinghbhadauria2818 10 месяцев назад

    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

  • @abuhossain4274
    @abuhossain4274 Год назад

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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.

  • @vinalkumar6934
    @vinalkumar6934 Год назад

    This was really helpful thanks.

  • @orelhindi8852
    @orelhindi8852 Год назад

    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?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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

  • @elinordeniz
    @elinordeniz Год назад

    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 RUclips. I am sure its something many people struggle with.
    Thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      I have a video on Serverless functions with Netlify here: ruclips.net/video/J7RKx8f4Frs/видео.html
      I will show how to deploy Next.js - including the REST API - later in this series.

  • @AntNZ
    @AntNZ Год назад

    Lookin forward to the middleware video 😊

  • @sonamohialdin3376
    @sonamohialdin3376 Год назад

    Very helpful tutorial thank you

  • @travisv6431
    @travisv6431 Год назад

    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.

  • @alsherifkhalaf7385
    @alsherifkhalaf7385 Год назад

    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 ?

  • @patite3103
    @patite3103 Год назад +1

    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?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

      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.

  • @nami07.03
    @nami07.03 Год назад

    is this not applicable in the latest next version? I tried DELETE method but can't received a message.

  • @stephenlau2845
    @stephenlau2845 Год назад

    Hi, Thanks for your Tutorial, How can I use API Routes database to one to one and one to many ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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.

  • @adelprog
    @adelprog Год назад

    Thanks for sharing 👍

  • @ofirlevy3682
    @ofirlevy3682 Год назад

    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?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

      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.

  • @NOTHING-en2ue
    @NOTHING-en2ue Год назад

    very nice tutorial ❤

  • @leoMC4384
    @leoMC4384 Год назад

    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??

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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.

  • @benzsfrancois1726
    @benzsfrancois1726 Год назад

    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 ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      You could but I think it does have some limitations - at least currently - compared to using a traditional Node.js/Express backend.

  • @ATOMICTRADER1
    @ATOMICTRADER1 Год назад

    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 🙏

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      My answer to this frequently asked question: ruclips.net/user/shortsc8tUBvaAP1A

    • @ATOMICTRADER1
      @ATOMICTRADER1 Год назад

      @@DaveGrayTeachesCodethanks ❤️🙏

  • @HunterAchieng
    @HunterAchieng Год назад

    quick question. i keep getting the url not found error each time. Is there something I am doing wrong?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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.

  • @GabJornacion
    @GabJornacion Год назад

    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?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

      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.

    • @GabJornacion
      @GabJornacion Год назад

      @@DaveGrayTeachesCode Thanks for replying! I probably missed what you said haha. But I appreciate your tutorials nonetheless!

  • @copilotcoder
    @copilotcoder Год назад

    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

  • @azharmahmood624
    @azharmahmood624 Год назад

    Impressed with your teaching skills Dave, really impressive, please keep it up. I hope will learn a lot from you.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

      Thanks, will do!

    • @azharmahmood624
      @azharmahmood624 Год назад

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

  • @monishbk5612
    @monishbk5612 Год назад

    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?

  • @studyplanet4656
    @studyplanet4656 Год назад

    That was really great tutorial , if possible can you make tutorial on access and refresh token in next js .

  • @theway_up
    @theway_up Год назад +1

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      This might be a good question to post in my Discord. Link in the description.

  • @MrArod1234
    @MrArod1234 Год назад

    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?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +3

      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.

    • @MrArod1234
      @MrArod1234 Год назад

      @@DaveGrayTeachesCode Great, thank you!

  • @alexanderkomanov4151
    @alexanderkomanov4151 Год назад

    Thanks a lot!

  • @sayidradhinpm8761
    @sayidradhinpm8761 Год назад

    You are much more awesome 🎉

  • @saswatpranat6748
    @saswatpranat6748 Год назад

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

  • @user-pk4vc9xw2n
    @user-pk4vc9xw2n Год назад

    Dave can you do a tutorial using next api with mongoose?

  • @zunnoorainrafi5985
    @zunnoorainrafi5985 Год назад

    Hi Sir,
    What icon theme are you using?

  • @demetrycode
    @demetrycode 11 месяцев назад

    love it

  • @includerajat
    @includerajat Год назад

    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);
    };
    ```

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      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.

  • @johny6767
    @johny6767 Год назад

    why are you not using getServerSideProps ,
    getStaticProps,
    getStaticPaths in the whole tutorial ?

  • @LyDaiPhatB
    @LyDaiPhatB Год назад

    next 13.4.6 DELETE method still error ~~, PUT method work :))

  • @stalomnanotape2967
    @stalomnanotape2967 4 месяца назад

    A REST Api with no route protection?

  • @codernerd7076
    @codernerd7076 Год назад +1

    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!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

      Agreed! That would make a good follow-up outside of this series.

  • @olajireabdullahi1196
    @olajireabdullahi1196 6 месяцев назад +1

    this is the wrong video title, It is supposed to be "How to connect with Rest API" not Build!!

  • @_rtdp_
    @_rtdp_ Год назад

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

  • @aliraza-zt8ef
    @aliraza-zt8ef Год назад +1

  • @etzumahkaya9583
    @etzumahkaya9583 Год назад

    Build api BEST bACKEND LANGUAGE JS IS MAKE TO FROONT DEV , IN Chile says pastry chef yo ypur cakes

  • @monzerfaisal3673
    @monzerfaisal3673 Год назад +1

    Dave. I am a straight man but i want to marry you xD

  • @jssyntax200
    @jssyntax200 Год назад

    Thanks so much sir.,
    Plese make video how to manage accessToken and refreshToken from express backend from your previous lesson ruclips.net/video/CvCiNeLnZ00/видео.html using nextauth in nextjs 13

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад

      Auth is a more advanced topic that I plan to tackle sometime after this fundamentals course is complete. 🚀

  • @dopetag
    @dopetag Год назад

    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
    }
    }

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Год назад +1

      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.