Why I Don't Use Next.js Server Actions to Fetch Client-Side Data

Поділитися
Вставка
  • Опубліковано 28 чер 2024
  • Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
    In this Next.js tutorial, I share why I don't use Next.js Server Actions to fetch client-side data. We'll look at how you can fetch data in a client component with a Next.js server action and alternative options, too.
    💖 Support me on Patreon ➜ / davegray
    ⭐ Become a full-stack web dev with Zero To Mastery Courses:
    - Complete Next.js Developer: bit.ly/CompNextJSDev
    - Advanced React: bit.ly/AdvReactDev
    - Junior to Senior Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
    🚩 Subscribe ➜ bit.ly/3nGHmNn
    📬 Course Updates ➜ courses.davegray.codes/
    ❓ Questions - Please post them to my Discord ➜ / discord
    ☕ Buy Me A Coffee ➜ www.buymeacoffee.com/davegray
    🔗 Source Code Example: github.com/gitdagray/nextjs-d...
    🔗 My Next.js Videos: • Next.js Tutorials for ...
    👇 Follow Me On Social Media:
    GitHub: github.com/gitdagray
    Twitter: / yesdavidgray
    LinkedIn: / davidagray
    Why I Don't Use Next.js Server Actions to Fetch Client-Side Data
    (00:00) Intro
    (00:10) Welcome
    (00:34) Discussion
    (01:02) Example App
    (04:52) Request & Response Details
    (06:03) Final Thoughts
    📚 Tutorial References:
    🔗 Next.js docs "Server Actions & Mutations": nextjs.org/docs/app/building-...
    🔗 MDN Cache-Control: developer.mozilla.org/en-US/d...
    Was this tutorial about fetching data with Next.js Server Actions helpful? If so, please share. Let me know your thoughts in the comments.
    #nextjs #server #actions

КОМЕНТАРІ • 125

  • @milosnedeljkovic3737
    @milosnedeljkovic3737 2 місяці тому +20

    The biggest drawback that I found in using server actions to fetch the data is that Next seems to have a built in queue for server actions requests. That means that server action requests are sent to network strictly sequentially, one by one. That also means that you cannot really fetch the data in parallel (for example, in two unrelated client components in the hierarchy).

  • @rnavedojr
    @rnavedojr 2 місяці тому +13

    Facts. NextJs is a messy cache issue. But still the best JS Framework by far IMO.

  • @ayukalvieri3154
    @ayukalvieri3154 2 місяці тому +26

    The point he said "this could all change next week", made me wanna change my code to use API routes instead of server actions

    • @jaatjii7823
      @jaatjii7823 2 місяці тому +4

      Do fetch data on server components and then pass it to client components.Server actions are good to use.😊

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      Those are two different things. Fetching data on the server and passing it to a client component is what I did in example one. Using the server action was example three.

    • @jaatjii7823
      @jaatjii7823 2 місяці тому

      @@DaveGrayTeachesCode hi sir…big fan❤️❤️❤️

    • @jaatjii7823
      @jaatjii7823 2 місяці тому

      @@DaveGrayTeachesCode if you pass objects form server components to client components make sure to stringfy the data as it gives some unusual errors.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      @@jaatjii7823 true. You usually send JSON data. In the server fetch example, I pass a simple string.

  • @johnpaulpineda2476
    @johnpaulpineda2476 2 місяці тому +2

    Hi Dave, wassup? I've been a subscriber since 50k. I'm so very glad you're already close to 300k.
    Keep up the good work Dave!

  • @enzocodes
    @enzocodes 2 місяці тому +1

    Hello Dave! Adding up to the mentioned in the video, I think using api routes is better if you plan to scale your app and consume the api from a mobile app. It gives more versatility, also if you are developing an app that will serve as an api for other apps, api routes is the way to go. In conclusion api routes give you more control for different scenarios.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      Yes, API routes can fit more needs. And without the documentation stating that server actions are for fetching, I hesitate to use them that way. I'm sticking with API routes when fetching from a client component for now as well.

  • @7doors847
    @7doors847 2 місяці тому +2

    Very insightful. More Next.Js quirks please. ☝️

  • @learner8084
    @learner8084 2 місяці тому

    I'm learning a lot from you. Thanks very much. I wonder if I should use React Hook Forms ? I'm previously using formik, MUI with React. But moving to Nextjs, I'm moving to also to ShadCN, Tailwind. ShadCN has Form component and it works with React Hook Forms. Should I move to this as well ?

  • @ZiaCodes
    @ZiaCodes 2 місяці тому +1

    Yes, I also thought about it and I'm using react-query to do a client side fetching for client components and inside that queryFn, I'm passing the server action...

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      It does work. I'm just not ready to start using server actions for data fetching due to the reasons I give in the video. I do use them for form submissions and data mutations.

  • @versaleyoutubevanced8647
    @versaleyoutubevanced8647 2 місяці тому +2

    If you wrap the server action promises in a useQueries and mutations, this would give you the cache control and the states around the promise state, like a tRPC Queries
    Server actions is a good primitive that should not be exclusive only to mutations, they should work around that or create something like 'use server query', 'use server mutation'

  • @mdhaiderhossain
    @mdhaiderhossain 2 місяці тому +1

    I think the next.js 14 server action and cache validation are not good because a few months ago i worked on a project where i had to use complex data queries for fetching data, and that worked very well, but the problem was that when i tried to revalidate the data, it was not working properly, & the next.js were calling the API infinitely in the network tab, but when i moved the scroll mouse on the window a little, it had been stopped. I have some more problems, and i have tried many times to solve them, but i can't.
    What do you think ? is next.js perfect for complex project?

  • @ChetsStore
    @ChetsStore 2 місяці тому

    Is there a way to utilize an API developed within my Next.js application? I've heard that it's impossible to access the data that comes from internally written API routes after deployment while everything works fine locally. Within API routes, I can only fetch data from external APIs.

  • @jasekdominik
    @jasekdominik 2 місяці тому +7

    I personally use this. The biggest benefit is full typesafety. This basically makes tRPC obsolete. Caching can be handled via react-query.
    The downside of this approach is debugging in the devtools. It's not clear which server action is called, what is the payload and the response. I hope there will be some extension for making this more convenient.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      I agree there are possible benefits. I'm just being cautious for now. I would like to see it supported with full documentation.

  • @user-wf4pr1jx8l
    @user-wf4pr1jx8l 2 місяці тому

    Great video!
    I have a situation where user would submit a form and i need to make POST request to an API which would return data. In that case, i am using server action and it works but I'm confused on whether i should be going that route or not.
    I would really appreciate your recommendation on this.😊
    Thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      Yeah I think that is fine. Server actions are meant for form submissions.

  • @MrRedwolf.
    @MrRedwolf. 2 місяці тому

    I have two components. Like mobile view component and monitor view component.Both same actions and content but design wise they have lots of changes.. using display property i can hide the components and show based on screen size. However it was big content assuming if we open the nextjs application in pc the mobile view component also renders into dom. But i want to improve our performance, so i want to render the components based on screen size during the dom mutation in react . So how to implement it. Can you please help me?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +2

      To do anything based on the screen (viewport) size, you will need to have a client component as a parent to the other components. Calculate the size from the window object - but caution! - this will throw an error in Next.js unless you do it inside a useEffect because even client components are prerendered on the server first. You can use React.lazy to import the child components to help minimize the bundle size, too.

  • @zacharyshifrel9107
    @zacharyshifrel9107 2 місяці тому

    I’m using an express server, and sometimes I’m using useEffect to fetch, but for more expensive stuff I’m using async fetch functions in server components which seems to work fine for now. Do you think this is alright?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      Yes, although I would choose SWR or React Query over useEffect in client components. A fetch function in a server component is the first method I show (aka Server Fetch) in this video. It's best when possible.

  • @zohaibakber3056
    @zohaibakber3056 2 місяці тому +1

    It totally depends, for instance I use a server action to get presigned url for file uploads to s3, which is much better than api route implementation tbh

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      It definitely works. That's why I wanted to show it here. That said, I also wanted to highlight some issues. It would be nice to see more documentation or at least acknowledged support. Right now, it feels like we're on our own and decisions could be made to break this at any time.

    • @PraiseYeezus
      @PraiseYeezus 2 місяці тому

      oh, this is a good usecase I hadn't thought of, thanks

  • @fscubetech7219
    @fscubetech7219 2 місяці тому +2

    The great content.

  • @Harshit.git911
    @Harshit.git911 2 місяці тому +1

    well said

  • @wishmeheaven
    @wishmeheaven Місяць тому

    Thanks!
    It might be a bit off topic, but if I may offer a couple of most desirable tutorial series:
    1. Astro.
    2. React v19 (at least SSR, new "compiler", new concepts..)
    A man can only hope,
    But even if it won't fulfilled -
    Thank you for everything, Dave 😇

  • @Tausif_Khan_07
    @Tausif_Khan_07 2 місяці тому +8

    Hi sir, please make a video on microservices architecture it's implementation and deployment process please.

  • @mkroven
    @mkroven 2 місяці тому +6

    If I need personalized data and need auth cookies I use client data fetch, if I need non frequently changing data and I dont need cookies I use server actions to fetch data. Vercel is pushing too hard NextJs limits to lower compiling and serving its apps. This is irritating devs from react. I am seriously waiting prod-ready versions of rust web frameworks like dixous or leptos to jump on. And Dave, I love watching your videos. Thank you.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      I understand! And thank you for the kind words!

    • @maskman4821
      @maskman4821 2 місяці тому

      I love Nextjs 14,it is so cool and easy to use ❤🎉

  • @fathur208
    @fathur208 2 місяці тому

    Why you should fetch from server action? Is server action purpose to mutate the data? Because if we mutate the data from api route, revalidatePath doesn't work for fetching in server component except you hard reload the browser or use window.location.replace

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +2

      Sounds like you are agreeing with me. I am not recommending to use a server action for fetching data even though it is possible.

  • @ianc6418
    @ianc6418 23 дні тому

    I'm new to this, I don't understand why server actions are there at all, maybe they are intended to replace the "action" property on forms, but aren't fully fleshed out yet? But if I can keep doing requests without it then I'm not gonna worry about it. Thanks for the example!

  • @AmodeusR
    @AmodeusR 2 місяці тому

    Isn't server actions supposed to be used in a form through the action property?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      That is not the only way they can be used. However, some are using them to fetch data, and while possible. I'm not currently going that far.

  • @emanuel_larini
    @emanuel_larini 2 місяці тому

    What's the point of using a SSR framework to fully rely on CSR? I do understand if you use react-query for query revalidation, but putting it to make even the initial request isn't just like going back to "old" react?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      Never said I was fully relying on CSR. My preference is "Server Fetch" - example 1 in the video. However, there are times when you need to request data inside a client component. When I need to, I'm not going to use server actions yet.

    • @emanuel_larini
      @emanuel_larini 2 місяці тому

      @@DaveGrayTeachesCodeI didn't mean you said it, sorry about it
      But shouldn't you just use RSC for those fetches?
      I think Vercel is exposing too many patterns to everyone without providing a guidance. Sounds very much like what the react team did with react itself, which is a big fail imho

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      @@emanuel_larini I use RSC whenever possible. This video has contrived examples to show each possibility. That said, I again say there are some instances where you want to fetch more data in a client component after the initial load. This is when I reach for an API route - only when fetching from a client component is deemed necessary.

  • @zedroofficial
    @zedroofficial 2 місяці тому

    then which is better ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      All 3 approaches work here. I explain why I'm not using a server action to fetch data from a client component yet.

    • @zedroofficial
      @zedroofficial 2 місяці тому

      @@DaveGrayTeachesCode then which one is you using?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      In the video, I said I am using the 1st two examples to fetch data but for now, I'm not fetching data with server actions. Give it a watch :)

  • @aodflash
    @aodflash 2 місяці тому

    if its stable in 14, then It should be fine?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      Server actions are stable but as I highlight in this video, they are stable for form submissions and data mutations. There is no documentation for directly fetching data with a server action.

  • @AlphaHydrae
    @AlphaHydrae 5 днів тому

    The real question is does a server action fetching data work with JS disabled in the browser? If it does then it seems like there's a progressive enhancement use case there.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 дні тому

      I like this question. It wouldn't work with something like useSWR or React Query - but maybe triggered with a form.

  • @27sosite73
    @27sosite73 2 місяці тому +4

    damn, it is my comment
    thank you mate
    you are the best

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +2

      Thanks! And thanks for the comment that made me investigate further!

  • @nasko235679
    @nasko235679 7 днів тому

    The one thing I still don't understand is how to fetch data SECURELY from a client component? What I mean by securely is checking for authentication/ authorization before providing the data. Are API routes still the way to go for that? Because using server actions is not meant for that purpose as you said (and they are getting queued) and simple helper functions won't work for the authentication part is just making an API route and doing the authentication/authorization check there the way to go? And yes I know you can fetch data from a server component and pass it down as props but that works for more static data, but if you need something more dynamic you kinda have to do it clientside.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  7 днів тому

      Yes, I check auth in every API route. I also check auth in server actions when doing mutations.

  • @maxpayne9074
    @maxpayne9074 2 місяці тому +1

    Source code example link don't work

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      Got it working now: github.com/gitdagray/nextjs-data-fetching

  • @suhailabdulla946
    @suhailabdulla946 2 місяці тому +1

    The GitHub link is not working ??

  • @karthikkhoday5555
    @karthikkhoday5555 2 місяці тому

    Server action are not nextjs feature but react feature, react is improving and new features are added, this actions will stay cause it makes stuff soo simple

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      I like them. I'm just not ready to fetch data with them yet in Next.js without more documentation and assurance they won't change how it works within the framework. They are stable for form submissions and mutations. If React (without Next) offers data fetching documentation for server actions, please share. I'm going to look, too!

  • @John-eq5cd
    @John-eq5cd 2 місяці тому

    Why is there a hesitation about fetching data with a server action, but not about mutating data with a server action?
    Is it simply when we fetch data we get it from the server and present it in the client whereas with mutating, we are updating, but not necessarily getting data from the server?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +2

      When mutating data, it is usually a form submission. You can call server actions without a form submission, but then you are likely just looking for a success or fail response - possibly with useOptimistic having already updated the UI. Absolutely, no documentation or recommendation in the docs to fetch initial or polling data with server actions.

    • @gravellife5643
      @gravellife5643 2 місяці тому

      @@DaveGrayTeachesCode I have playSlot($backgroundPositions) server action calling from client component. This action return win amount and new symbols positions where to stop slot animations calculated on server. On server I keep current game data in redis json. Its working just fine.

  • @planesrift
    @planesrift 2 місяці тому +1

    I feel that Next.js is a bit overengineering. Anyway, I think why server action works that way is because it is a workaround for server component by nature.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      Agreed. I'm just not comfortable with fetching data using a server action until it's documented. Otherwise, they could make a change that breaks it next week.

  • @incarnateTheGreat
    @incarnateTheGreat 2 місяці тому

    I learned using a Sever Action to retrieve data and did not like it.
    Not long after, Lee (or someone else) had released a video explaining that you can co-locate your page.tsx file to have the default function make a server-side call to an async function that retrieves the data using fetch in a try-catch.
    Honestly, I much prefer this method over Server Actions. Server Actions should be reserved for things such as Form actions.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      Yes, server component fetch is the way to go. If you need to fetch _more_ data after the server fetch while staying on the same page - maybe on-demand product details or similar - the choice becomes server action or API route.

  • @togya4
    @togya4 2 місяці тому

    Dave pleaseeeee leave the src code

    • @togya4
      @togya4 2 місяці тому

      Its giving 404 in github​@@DaveGrayTeachesCode

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      Here it is: github.com/gitdagray/nextjs-data-fetching

  • @weirddev
    @weirddev 2 місяці тому +1

    It does not feel good

  • @IINoirII
    @IINoirII 2 місяці тому +2

    I guess, App router is not even ready for production...

    • @fathur208
      @fathur208 2 місяці тому +1

      I think so, server action can't handle complex form. So for now i use antd Form to handle server action with complex form

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      I'm using the App Router in production. I'm just not recommending that you fetch data with a server action. Server actions are good for form submissions and for mutating data.

    • @fathur208
      @fathur208 2 місяці тому

      @@DaveGrayTeachesCode How do you perform complex form submission, such as if the form contains data input array of objects?

    • @sudhanshubhagwat9538
      @sudhanshubhagwat9538 2 місяці тому

      @@fathur208as far as I know, this cannot be done right now with form actions

    • @oscarljimenez5717
      @oscarljimenez5717 2 місяці тому

      ​@@fathur208you have ways, but if you don't wanna go to hard, just make it client component using a Form Library and use the server action there.

  • @jasonjimenez9116
    @jasonjimenez9116 2 місяці тому

    it all boils down to best practices. nextjs should be up front what their intention with server actions, what problem they are trying to solve. otherwise it is better to play it safe coz right now nextjs14 looks like an unfinished experiment. generating a server and client on one code base is really a stretch IMO. the fact that dev and prod build dont yield same behavior is a red flag.

  • @user-re7zb6oo2s
    @user-re7zb6oo2s 2 місяці тому

    What nonsense I just heard. Server actions are needed for forms or changing data, not for receiving it. That's why there is always POST and not GET. In hooks like useSWC/useQuery asynchronous functions are executed anyway. And to get data, server-side components are used to get the initial data for quick display, and then different functionality is implemented. useQuery even has an initialData field for such cases.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      Sounds like you agree with me. If you "heard" this, it means you listened to the video, right? I agree with "not for receiving it" which is why I'm not using server actions to fetch data even though it is possible.

    • @user-re7zb6oo2s
      @user-re7zb6oo2s 2 місяці тому

      @@DaveGrayTeachesCode Ideally yes, I heard it wrong. I first thought you were wondering why you can't use server actions to retrieve data. About the POST thing, I thought you were wondering why server actions have a POST method and not a GET method.

    • @jt71955
      @jt71955 2 місяці тому

      No sorry Dave?​@user-re7zb6oo2s

  • @user-ec9kn7id1n
    @user-ec9kn7id1n 2 місяці тому

    Dave speaks better as a native speaker

  • @chrisr2063
    @chrisr2063 2 місяці тому

    I use server actions in my context. Fight me

  • @shawnxiong2011
    @shawnxiong2011 2 місяці тому +1

    server action is too much magic, it's a good experimental feature to play, and used for casual project, definitly no go to real product for me.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      I like server actions for form submissions and data mutations. I'm just not ready to fetch data with them yet as it doesn't seem to be an intended (or documented) use.

    • @vitosnatios
      @vitosnatios 2 місяці тому

      Server actions are stable.

    • @shawnxiong2011
      @shawnxiong2011 2 місяці тому

      @@vitosnatios yeah, Nextjs recently claim many features as stable releases, but as general practise not to rush the new features into production.

  • @kenshinhimura3140
    @kenshinhimura3140 2 місяці тому

    My friend there is no tutorial on internet about csp on next js 😢

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      Found this: nextjs.org/docs/app/building-your-application/configuring/content-security-policy

    • @kenshinhimura3140
      @kenshinhimura3140 2 місяці тому

      @@DaveGrayTeachesCode 😑
      Every body don't care about csp in fact.
      I read the doc and I talk with the vercel staff and same thing they don't care about security.
      Fuck nextjs

  • @jouiedomar1922
    @jouiedomar1922 2 місяці тому

    How to secure POST handler function using csrftoken like what Django doing?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +1

      When you POST data using a Server Action, it is very secure because it is not using an API route URL at all. It uses an imported server action function. I do recommend server actions for posting form data in Next.js. Django uses a CSRF token because it does POST to a traditional URL. Django wants to confirm that POST is coming from the intended website.

    • @jouiedomar1922
      @jouiedomar1922 2 місяці тому

      @@DaveGrayTeachesCode thank you dave, but there is a way to do this (csrftoken validation) in nextjs as well?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому +2

      This Next.js blog article talks more about CSRF and Next.js: nextjs.org/blog/security-nextjs-server-components-actions

  • @kenshinhimura3140
    @kenshinhimura3140 2 місяці тому

    Tell me how to refresh a server component in the user screen without refresh the page and without react query?
    I use revalidatePAth but on the screen the server component did not refresh without refreshing the screen.
    Help me and I subscribe and I make a donation to your patreon 😊

    • @joyahmed1269
      @joyahmed1269 2 місяці тому

      revalidate

    • @kenshinhimura3140
      @kenshinhimura3140 2 місяці тому

      @@joyahmed1269 with revalidatePAth and others data will be refresh in the server but not on the user screen, you will need to refresh the browser, that is what we don't want

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 місяці тому

      @kenshinhimura3140 Here you go: github.com/gitdagray/server-action-todos ..follow the directions in the README. This will add new todos to your database and displayed list without refreshing the page and without react query or swr. Bonus: it will continue to work even if you disable JavaScript.

    • @kenshinhimura3140
      @kenshinhimura3140 2 місяці тому

      @@DaveGrayTeachesCode thanks Dave Great

    • @heracraft5526
      @heracraft5526 2 місяці тому

      import { useRouter } from "next/navigation";
      const router=useRouter();
      whenever you want to refresh the server component, for example you want it to re-fetch some data to show updates call `router.refresh()`. I hope this works for you