简体   繁体   中英

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.

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 .

You can set the cookies on serverside that will be accessible on client side as well once created.

import { serialize } from 'cookie'

export async function getServerSideProps(context) {
  const { res } = context;
  res.setHeader('Set-Cookie', serialize('token', 'abcdefg', {
    httpOnly: true,
    maxAge: 60 * 60, // 1 hour
    path: '/',
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
  }))
  return { props: {} }
}

Checkout this link for more info https://developershift.com/optimizing-next.js-performance-with-getserversideprops-fetching-data-on-server-side-in-next.js/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM