Search code examples
javascriptreactjsnext.jsserver-side-rendering

How do i store data in nextjs that is accessible from anywhere


I have a nextjs app that needs to make api requests based on the user's inputs. Now the api requests need a token that I would like to generate at the start of the app and anytime that i need to based on the user data from getServerSideProps or something. I looked at a lot of options like saving it in cookies and session but i don't think for my use case that serves the purpose plus i would also like to learn how it should be done in nextjs. Basically I need a

const data = {}

accessible from each request on the server so that when the server gets a request it does not have to refetch the data it already has.


Solution

  • This is a good question.

    Static data

    If you have a static data, then your solution speaks for itself. Just export that so that all other files can import.

      const data = {}
      export default data
    

    Client data

    However in your case, you are speaking of static, but the data isn't, ex. the user info have to be resolved by one of the API and then stored somewhere as "static" from now on. So it's not static.

    In case it's a client side (cookie), you can wire with that variable directly, such as in Next Auth. https://next-auth.js.org/getting-started/example

    Server data

    If it's server data, it needs to be persisted via one of your API /pages/api. And after that yes, you can put it via getServerSideProps to the _app.js.