Why you can't set cookies in Server Components

แชร์
ฝัง
  • เผยแพร่เมื่อ 18 ม.ค. 2025

ความคิดเห็น • 105

  • @jordancutler7552
    @jordancutler7552 11 หลายเดือนก่อน +6

    Such an undersubscribed channel.
    Learned an insane amount from this video. Thank you for what you do, Ryan!

  • @Aaronmoreno
    @Aaronmoreno 7 หลายเดือนก่อน +2

    Ryan, this is a game changer explination. So glad I found this channel. So well broken down

    • @RyanToronto
      @RyanToronto  6 หลายเดือนก่อน

      Thanks!!!

  • @codinginflow
    @codinginflow 5 หลายเดือนก่อน +1

    This was very enlightening. Another place to set cookies is in route handlers!

  • @onyeukwuhycient438
    @onyeukwuhycient438 2 หลายเดือนก่อน +1

    Awesome insight.
    This just saved me a huge stress of tinkering around.

  • @sagarchilivery6112
    @sagarchilivery6112 11 หลายเดือนก่อน +2

    Thanks Ryan, keep uploading we love your videos!

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน +1

      Glad to hear it! I've got a few more videos based around RSCs that will be coming soon!

  • @VitorVelosoSA
    @VitorVelosoSA 11 หลายเดือนก่อน +1

    Nice video! I got into this issue and never understood why I couldn’t do it

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน

      Glad you liked it!

  • @adwaitbokade2890
    @adwaitbokade2890 11 หลายเดือนก่อน

    Thanks man, you solved my bug because I got pissed of from last 2 days !!
    Please bring more about react server components !!

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน

      Awesome glad it helped!

  • @ElHawary
    @ElHawary 7 หลายเดือนก่อน

    Thank you, I was actually watching this in a private window "doing some testing", I had to login just to like and sub.

    • @RyanToronto
      @RyanToronto  7 หลายเดือนก่อน +1

      Wow thanks for the kind words! Really appreciate it!

  • @JerryHu-i5r
    @JerryHu-i5r หลายเดือนก่อน +1

    Why can't you send cookies on the initial page serve? Since you are sure that no additional streaming is happening for the initial HTML?

    • @RyanToronto
      @RyanToronto  หลายเดือนก่อน

      That's a great question. You technically could, but if your code ever got moved inside of a Suspense boundary then it would all of a sudden stop working. So Next takes a hard line about setting cookies during render.

    • @JerryHu-i5r
      @JerryHu-i5r หลายเดือนก่อน

      @@RyanToronto Thanks for the reply, yeah I am not a big fan of setting the cookies on the middleware only since it runs on every route. In this case I have token refreshing logic when entering some private routes implemented, so it would be nice to do this on the initial page render. Currently have no choice but to place it on the middleware.

  • @ColynBrown
    @ColynBrown 8 หลายเดือนก่อน +1

    I remember back in my PHP days we were constantly presented with "Headers already set" if we ever tried to set a cookie after the headers were set. Not sure why we can't be presented with the same error if we tried doing that

    • @RyanToronto
      @RyanToronto  8 หลายเดือนก่อน

      Oh that's a very neat idea

  • @toomanyarguments
    @toomanyarguments 11 หลายเดือนก่อน

    a brilliant and advanced video. thank you

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน

      Glad you liked it!

  • @kanasva
    @kanasva 7 หลายเดือนก่อน

    Best explaination on earth. Thanks

    • @RyanToronto
      @RyanToronto  6 หลายเดือนก่อน

      Thank you!

  • @tofazzalhaque3613
    @tofazzalhaque3613 4 วันที่ผ่านมา

    Great video! I struggled with this issue for a while and couldn’t figure out why it wasn’t working. Could you suggest a way to store the access token and refresh token in a server component? Specifically, while the server component is rendering, the access token might expire and need to be refreshed and stored again after obtaining a new one.
    Currently, I’ve used ioredis, but it’s not supported in middleware, and I don’t think it’s ideal for this use case. Is there a better solution that works with the Edge Runtime and allows setting cookies directly from the server component?
    Thanks again, Ryan!

    • @RyanToronto
      @RyanToronto  4 วันที่ผ่านมา

      Glad to hear the video helped!
      That's a tough one and I think it can be hard to solve. I've run into a whole bunch of node libraries that won't run on edge runtime as well. Usually what I do is setup a node server and then have my edge runtime code make fetch requests to that node app. Then the node app can talk to redis using ioredis. It adds an extra hop, but if the node app and next app are running close to each other you can minimize latency. I know it's not a great approach, but it's hard to find good solutions with edge runtime.
      Another option would be to find a redis server that can work with `fetch`, since fetch is the way to do IO in middleware today.
      Sorry to hear you're having trouble with middleware. I'd be very curious to know what kind of solution you come up with. I don't know how to solve these types of problems well.

    • @tofazzalhaque3613
      @tofazzalhaque3613 3 วันที่ผ่านมา

      ​ @RyanToronto The concern is that we can't update cookie in the server component, so we can't store the tokens in cookie. At this moment, Redis comes into the picture, and Redis can be managed by using 'API and fetch' from middleware. Still, it doesn't feel like a good or optimal solution. I hope you will research more and come up with a good solution.😊

  • @joepetrillo6185
    @joepetrillo6185 4 หลายเดือนก่อน

    Very good video thank you!

  • @athar-q
    @athar-q 4 หลายเดือนก่อน

    But middleware is invoked for everyone request made from browser. Do we want to cookie-setting-logic to run on every request?

    • @RyanToronto
      @RyanToronto  4 หลายเดือนก่อน

      Check out the matching paths section of the Next.js docs to control which paths middleware should run on: nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths

  • @silverlila
    @silverlila 9 หลายเดือนก่อน

    Great content, I really like the way you explain in such simple terms.
    Also noticed your @twofold/framework which seems great, have you thought on making a course on how something like that could be created?

    • @RyanToronto
      @RyanToronto  9 หลายเดือนก่อน +1

      Thank you! Ya that's a great idea for a course. I think once React 19 is released there will be a great teaching story for RSC from scratch.

  • @Dreamer4777
    @Dreamer4777 8 หลายเดือนก่อน

    THANK YOU, this video really helped me.

    • @RyanToronto
      @RyanToronto  8 หลายเดือนก่อน

      Glad it helped!

  • @huntersgaming447
    @huntersgaming447 หลายเดือนก่อน

    All good !
    but I have one doubt if I need to set the cookie not after the app initialisation(middleware) but rather after a function(server action) works, for example user authentication setting tokens , traditionally the cookies has to be set after the storage of user details in the database, So uh how to implement this particular method, any solutions

    • @RyanToronto
      @RyanToronto  หลายเดือนก่อน

      Great question! You can totally set a cookie in a server action! Once you write data to the database call cookies().set right inside the action. It should just work :)

    • @huntersgaming447
      @huntersgaming447 หลายเดือนก่อน

      @RyanToronto will try it out

  • @godkid.
    @godkid. 10 หลายเดือนก่อน

    what if we want to save data gotten from our backend server to cookies how do we do that with the nextjs middleware?

    • @RyanToronto
      @RyanToronto  10 หลายเดือนก่อน

      I believe you can fetch data from your backend inside of the middleware function, then use that to set the cookie.

    • @godkid.
      @godkid. 10 หลายเดือนก่อน

      Ohh alright thanks@@RyanToronto

    • @godkid.
      @godkid. 10 หลายเดือนก่อน

      @@RyanToronto i would still love a platform to discuss with you on some other questions i have, where can i dm you ?

  • @ArunJenson-r5u
    @ArunJenson-r5u 11 หลายเดือนก่อน

    can you share how to set the cookie in server using route handlers?

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน

      Check out these Next.js docs: nextjs.org/docs/app/building-your-application/routing/route-handlers#cookies

  • @helljohn211
    @helljohn211 11 หลายเดือนก่อน

    Ryan this is really good information 👌

  • @ernestmalcolm7406
    @ernestmalcolm7406 4 หลายเดือนก่อน

    A very great video. One issue I have faced and wish to understand, what about setting the expiry time for that cookie, lets say a userToke, which is essential so when it expires it can be cleared. Hope the question makes sense. Hoping to hear from you soon

    • @RyanToronto
      @RyanToronto  4 หลายเดือนก่อน

      Great question! You can use the `maxAge` or `expires` option from Next's cookies().set function. See more details here: nextjs.org/docs/app/api-reference/functions/cookies#options

  • @tejasyoutuber
    @tejasyoutuber 9 หลายเดือนก่อน

    Hi Ryan,
    Thanks for the detailed explanation on cookies.
    I am having one problem with cookies.
    I am setting cookies in middleware in response and setting of cookies will happen to particular route only. After setting the cookies, i am accessing the cookies in my navbar using next/headers. Every time i try to access the cookies i am getting old value and not the updated values that is being set in middle ware.
    Why is that? Can you please tell me what is the wrong here.

    • @RyanToronto
      @RyanToronto  9 หลายเดือนก่อน

      Hmm, sounds like there might be a bug somewhere! Have you tried making a minimal reproduction that highlights the issue?

    • @tejasyoutuber
      @tejasyoutuber 9 หลายเดือนก่อน

      @@RyanToronto No, I didn’t try in minimal app.
      May be i will check it out.
      I want to know is that possible to get updated value which is being set in the cookies through middleware.
      Example: i added the middleware and inside it i am setting the cookies which is next url path. I added the config which is /about (so this middleware is run only in about page). Now when i access the about page, cookies will set through middleware, now i want to access that cookie in about page. Every time i try to access that cookie i get old value not newly set cookie through middleware.

  • @akopaaa
    @akopaaa 6 หลายเดือนก่อน

    but then, how do i set a cookie from my api ? like i would like to update the session ID of the user of my website, and i can't seem to find how to save a cookie on their browser with the session id from the api request... because :
    cookies().set( bla bla bla ) will just set the cookie for the response but then it gets lost

    • @RyanToronto
      @RyanToronto  6 หลายเดือนก่อน

      cookies.set should do it! Take a look at the docs, you might need some options like how long until it expires: nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options

    • @akopaaa
      @akopaaa 6 หลายเดือนก่อน +1

      @@RyanToronto yes, already tried but the request comes from a server component so it only sets the cookie on the reply. Anyway i solved my problem so it doesnt really matter anymore, thanks for the help though :D

    • @pedromigacz
      @pedromigacz 4 หลายเดือนก่อน

      @@akopaaa How did you manage to solve it?

  • @nrjdalal
    @nrjdalal 6 หลายเดือนก่อน

    bruh godly content

  • @bahaalmomani-jo
    @bahaalmomani-jo 10 หลายเดือนก่อน

    So how you can set a cookie based on a third-party API response you called inside your server component?

    • @RyanToronto
      @RyanToronto  10 หลายเดือนก่อน

      Hmm that's a good question! Could you make the API call in a middleware and use that to set the cookie? Then read it in the server component if you need the value

    • @bahaalmomani-jo
      @bahaalmomani-jo 10 หลายเดือนก่อน

      @@RyanToronto unfortunately thats not an option in my case, as I have a lot of APIs that will return a data needs to be stored in cookies, so I wonder what could be the best practice in that case?

  • @JIPPOKIKKA
    @JIPPOKIKKA 8 หลายเดือนก่อน

    How about if you do Cookie Banner for asking permission for users to use cookies.

    • @RyanToronto
      @RyanToronto  8 หลายเดือนก่อน

      For a cookie banner use a server action to set the cookie when they click the accept button.

  • @siya.abc123
    @siya.abc123 11 หลายเดือนก่อน

    Thanks for sharing man!

  • @manasranjansingh4374
    @manasranjansingh4374 5 หลายเดือนก่อน

    How to get cookies from browser in server component/server actions so we can send the cookies with request to backend API request.
    Please 🙏 reply I'm not able to find any solution

    • @RyanToronto
      @RyanToronto  4 หลายเดือนก่อน

      cookies().get('name') should allow your server component to get cookies from the incoming browser request.

  • @mauricedebeijer
    @mauricedebeijer 11 หลายเดือนก่อน

    And RSC's can be rendered at build time in some cases.

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน

      Yup great point!

  • @fratelo9832
    @fratelo9832 6 หลายเดือนก่อน

    You forget to say that Middleware slow down app because it rerender every time when you change a route. I am trying to set cookie without midlware but can't find solution

    • @lukevinicius
      @lukevinicius 4 หลายเดือนก่อน

      Do you finded some solution?

  • @maskman4821
    @maskman4821 11 หลายเดือนก่อน

    Sir,how do we implement theme switcher by using cookie so that when page gets refreshed users wont see a flicker/flash or a blank screen before theme got changed in nextjs 14 app router 🙏

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน +1

      Great question! For this one I think I'd read the cookie while rendering a server component and use that to control the theme. You can read more about reading cookies in Next.js here: nextjs.org/docs/app/api-reference/functions/cookies#cookiesgetname

    • @prohacker5086
      @prohacker5086 11 หลายเดือนก่อน +1

      You can read the cookie in server components, just can't set it. If you want to set it, you have to call server action from a client component. So if you want to set the cookie in a server component, you can use a Provider (client component) and pass the values you want to set to that provider so that it can call a server action to set the cookie.

    • @maskman4821
      @maskman4821 11 หลายเดือนก่อน

      @@prohacker5086 Thank you for the reply, it would be best illustrated with a sample codes 🥰

  • @NetraPatwari
    @NetraPatwari 8 หลายเดือนก่อน

    Hey man ... I have a problem.
    i m using server actions to set cookies , with "use server" at top, i have created a actions directory in my-app , and have all my server side actions there.
    still i m facing this error. "" [Error]: Cookies can only be modified in a Server Action or Route Handler."".
    Actually my backend is in python (fastapi) and it worked fine last time , with same tech stack.
    this time i have made 2 routes also , for stripe webhook..,
    How can i solve this ...

    • @RyanToronto
      @RyanToronto  8 หลายเดือนก่อน

      Oh that's strange, setting cookies in server actions should absolutely work! I would try opening a bug report with a reproduction showing the error. Sorry I couldn't be of more help!

  • @stevebendersky2056
    @stevebendersky2056 11 หลายเดือนก่อน

    Why haven't you imported the cookies fron next?

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน

      I'm not sure what you mean? This video initially uses next cookies, and then uses next middleware to solve the problem.

    • @stevebendersky2056
      @stevebendersky2056 11 หลายเดือนก่อน

      You import cookies from twofold/framework/cookies, why not from nextjs? import {cookies} from next/headers @@RyanToronto

  • @mounir101
    @mounir101 10 หลายเดือนก่อน

    Subscribed, can I protect routes with Middleware using encrypted user data stored in Cookies? thanks a lot and keep up the good work.

    • @RyanToronto
      @RyanToronto  10 หลายเดือนก่อน

      I think so! I would need to hear more, but I think signed cookies that are verified in middleware is a great place to start!

  • @PrasadKumkar-t3z
    @PrasadKumkar-t3z 2 หลายเดือนก่อน

    Thank you

  • @GANGORBANGORHOLDON
    @GANGORBANGORHOLDON 10 หลายเดือนก่อน

    Hi, man. I have a problem with cookies. I have backend api(i dont want to use next as backend) and I want to send on my backend from my next app request when web site is loading I try do it on server components but in this case cookies are not transmitted(Cookies have refresh token and access token). How to slove it? Or do I need ti make a request from client component? Sorry for my English, I just started learning English :)

    • @RyanToronto
      @RyanToronto  10 หลายเดือนก่อน

      That's great english from someone who just started learning!
      I think I would read the cookie (and the refresh token) in Next.js and then pass it to the fetch() call that Next is making when talking to your backend. Give that a try and let me know how it goes!

    • @GANGORBANGORHOLDON
      @GANGORBANGORHOLDON 10 หลายเดือนก่อน

      @@RyanToronto thank you, i will try it)

    • @GANGORBANGORHOLDON
      @GANGORBANGORHOLDON 10 หลายเดือนก่อน

      @@RyanToronto Hi again, I understood how cookies works in nextjs, but now I have the problem is with the server components. For example, I try to get private data, if access token expired, I fetch refresh token to endpoint /refresh and if response is successfull I try set new tokens in cookies but like you said I can't set cookies from server components. What solution would you suggest? Or I need to fetch from client components?

  • @cb73
    @cb73 8 หลายเดือนก่อน

    This is awesome thanks… I was literally just working on this.
    I ran into an issue trying to encrypt the cookies. The crypto library isn’t available in middleware because of the edge runtime. But… the web api for crypto is available which I’m working on now.

    • @RyanToronto
      @RyanToronto  8 หลายเดือนก่อน

      Nice! Did the web api end up working out for you?

    • @cb73
      @cb73 8 หลายเดือนก่อน

      @@RyanToronto no lol. Too hard. I’m already using a separate api written in golang that handles auth so I just wrote an endpoint that does the encryption (much easier in golang) - I call that in the middleware to give me the encrypted string I need to write a cookie. Works perfect for me.

  • @yoyomomma
    @yoyomomma 11 หลายเดือนก่อน

    Thank you!

  • @setasan
    @setasan 11 หลายเดือนก่อน

    Can we use server components without next.js or implementing it ourselves? I mean, with pure React running react-scripts. Great vid.

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน +2

      Thanks! In order to use RSC you'll need a build tool, so it's more work than dropping a script tag into your HTML file. You could implement it yourself, but there's a lot involved. Right now Next.js is one of the best implementations of RSC.

  • @salos1982
    @salos1982 4 หลายเดือนก่อน

    That is such an awful reason why I cannot set cookies in the page server component. Why can I not set it before calling any Suspense? This solves the issue. And only if you using Suspense then I cannot set any cookies

    • @RyanToronto
      @RyanToronto  4 หลายเดือนก่อน

      I believe the reasoning is that if you ever refactor your page into one that uses suspense all the cookie code would then break. Middleware is a recommended way to do it from Next.js.

  • @victorajayi9056
    @victorajayi9056 11 หลายเดือนก่อน

    Really good video!

  • @volodymyrzabelskyi5520
    @volodymyrzabelskyi5520 หลายเดือนก่อน

    thanks

  • @saifmohammad733
    @saifmohammad733 10 หลายเดือนก่อน

    Great tutorial. you should start an ASMR channel! voice is so relaxing.😅

  • @darren_baldwin
    @darren_baldwin 11 หลายเดือนก่อน +4

    This is exactly why RSCs will never be used for real fully-fledged backends - its use-case will mainly be as a BFF and proxying to another api/backend server somewhere else

    • @sadiqshaik4064
      @sadiqshaik4064 11 หลายเดือนก่อน +1

      Whats BFF?

    • @Nikich13v
      @Nikich13v 11 หลายเดือนก่อน

      @@sadiqshaik4064 backend for frontend

    • @ИмяФамилия-х4в1е
      @ИмяФамилия-х4в1е 11 หลายเดือนก่อน

      ​@@sadiqshaik4064"Backend For Frontend"

    • @RyanToronto
      @RyanToronto  11 หลายเดือนก่อน +1

      Using RSCs in BFF apps can work really well.
      I hope in the future as RSCs get used by more-and-more apps we'll be able to improve some of these APIs and make it easier to do all of the things that backend apps can do already.
      What kind of React apps are you working on these days? Do you have a BFF setup?

    • @jollyJedi
      @jollyJedi 11 หลายเดือนก่อน

      @@sadiqshaik4064backend for front end kind of a middle ground between a backend server and the front end.

  • @espritcritik
    @espritcritik 14 วันที่ผ่านมา

    Thank you 👌