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

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

Пікірлер: 118

  • @milosnedeljkovic3737
    @milosnedeljkovic3737Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Great observation!

  • @rnavedojr
    @rnavedojrАй бұрын

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

  • @ayukalvieri3154
    @ayukalvieri3154Ай бұрын

    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

    Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    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

    Ай бұрын

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

  • @jaatjii7823

    @jaatjii7823

    Ай бұрын

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

    Ай бұрын

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

  • @johnpaulpineda2476
    @johnpaulpineda2476Ай бұрын

    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!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Thank you! 🙌

  • @wishmeheaven

    @wishmeheaven

    26 күн бұрын

    You mean: "Keep striving for progress over perfection".. 😏

  • @enzocodes
    @enzocodesАй бұрын

    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

    Ай бұрын

    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Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Thanks!

  • @versaleyoutubevanced8647
    @versaleyoutubevanced8647Ай бұрын

    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'

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Great points!

  • @learner8084
    @learner8084Ай бұрын

    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 ?

  • @jasekdominik
    @jasekdominikАй бұрын

    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

    Ай бұрын

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

  • @mdhaiderhossain
    @mdhaiderhossainАй бұрын

    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Ай бұрын

    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.

  • @ZiaCodes
    @ZiaCodesАй бұрын

    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

    Ай бұрын

    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.

  • @wishmeheaven
    @wishmeheaven27 күн бұрын

    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 😇

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    26 күн бұрын

    Thanks for the requests!

  • @MrRedwolf.
    @MrRedwolf.Ай бұрын

    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

    Ай бұрын

    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Ай бұрын

    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

    Ай бұрын

    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.

  • @user-wf4pr1jx8l
    @user-wf4pr1jx8lАй бұрын

    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

    Ай бұрын

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

  • @zohaibakber3056
    @zohaibakber3056Ай бұрын

    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

    Ай бұрын

    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

    Ай бұрын

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

  • @fscubetech7219
    @fscubetech7219Ай бұрын

    The great content.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Thank you!

  • @mkroven
    @mkrovenАй бұрын

    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

    Ай бұрын

    I understand! And thank you for the kind words!

  • @maskman4821

    @maskman4821

    Ай бұрын

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

  • @fathur208
    @fathur208Ай бұрын

    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

    Ай бұрын

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

  • @emanuellarini
    @emanuellariniАй бұрын

    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

    Ай бұрын

    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.

  • @emanuellarini

    @emanuellarini

    Ай бұрын

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

    Ай бұрын

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

  • @Tausif_Khan_07
    @Tausif_Khan_07Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Thanks for the request.

  • @stephenchukwuani9481

    @stephenchukwuani9481

    Ай бұрын

    Traversy media just made a video

  • @Harshit.git911
    @Harshit.git911Ай бұрын

    well said

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Thank you!

  • @incarnateTheGreat
    @incarnateTheGreatАй бұрын

    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

    Ай бұрын

    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.

  • @AmodeusR
    @AmodeusRАй бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    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.

  • @27sosite73
    @27sosite73Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

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

  • @karthikkhoday5555
    @karthikkhoday5555Ай бұрын

    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

    Ай бұрын

    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!

  • @aodflash
    @aodflashАй бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    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.

  • @suhailabdulla946
    @suhailabdulla946Ай бұрын

    The GitHub link is not working ??

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Thanks! I'll have to check this.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Got it working now: nextjs.org/blog/security-nextjs-server-components-actions

  • @John-eq5cd
    @John-eq5cdАй бұрын

    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

    Ай бұрын

    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

    Ай бұрын

    @@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Ай бұрын

    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

    Ай бұрын

    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.

  • @maxpayne9074
    @maxpayne9074Ай бұрын

    Source code example link don't work

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

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

  • @zedroofficial
    @zedroofficialАй бұрын

    then which is better ?

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    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

    Ай бұрын

    @@DaveGrayTeachesCode then which one is you using?

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

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

  • @jasonjimenez9116
    @jasonjimenez9116Ай бұрын

    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.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Many agree!

  • @IINoirII
    @IINoirIIАй бұрын

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

  • @fathur208

    @fathur208

    Ай бұрын

    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

    Ай бұрын

    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

    Ай бұрын

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

  • @sudhanshubhagwat9538

    @sudhanshubhagwat9538

    Ай бұрын

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

  • @oscarljimenez5717

    @oscarljimenez5717

    Ай бұрын

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

  • @togya4
    @togya4Ай бұрын

    Dave pleaseeeee leave the src code

  • @togya4

    @togya4

    Ай бұрын

    Its giving 404 in github​@@DaveGrayTeachesCode

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

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

  • @user-re7zb6oo2s
    @user-re7zb6oo2sАй бұрын

    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

    Ай бұрын

    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

    Ай бұрын

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

    Ай бұрын

    No sorry Dave?​@user-re7zb6oo2s

  • @weirddev
    @weirddevАй бұрын

    It does not feel good

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    Agreed

  • @chrisr2063
    @chrisr2063Ай бұрын

    I use server actions in my context. Fight me

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    😂 to each their own!

  • @user-ec9kn7id1n
    @user-ec9kn7id1nАй бұрын

    Dave speaks better as a native speaker

  • @shawnxiong2011
    @shawnxiong2011Ай бұрын

    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

    Ай бұрын

    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

    Ай бұрын

    Server actions are stable.

  • @shawnxiong2011

    @shawnxiong2011

    Ай бұрын

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

  • @kenshinhimura3140
    @kenshinhimura3140Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

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

  • @kenshinhimura3140

    @kenshinhimura3140

    Ай бұрын

    @@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Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

    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

    Ай бұрын

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

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Ай бұрын

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

  • @kenshinhimura3140
    @kenshinhimura3140Ай бұрын

    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

    Ай бұрын

    revalidate

  • @kenshinhimura3140

    @kenshinhimura3140

    Ай бұрын

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

    Ай бұрын

    @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

    Ай бұрын

    @@DaveGrayTeachesCode thanks Dave Great

  • @heracraft5526

    @heracraft5526

    Ай бұрын

    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