简体   繁体   中英

Next.js fetch a token from an api on initial render and store it

I'm building an application using next.js, there is a need to fetch a guest token from an api and set in the cookie as it would be needed throughout the application. So the first thing I want is the token to be set in the cookie before any page is loaded.

I'm migrating from react, there this logic was there in the app.js file and it was a single page application.

I tried putting the logic in getServerSideProps in the home page, it worked fine and the cookie was set, but the issue was if the user go to any other page first directly, the cookie won't be there. To achieve that we have to duplicate this code in that page as well. (which I don't want as there are lot of pages)

Then on further research, I came to know that we can use getInitialProps in the _app file, that fetches the initial data for all the pages but it comes with a warning (This disables the ability to perform automatic static optimization, causing every page in your app to be server-side rendered.) Not sure if it would be ideal for this case.

Is there any other solution, like some kind of wrapper we can use on top of _app to fetch the token server side and store it. I'm new to next.js, please help me with this.

If you want to share the same server side logic to all the pages you could use next middleware or next custom server .

Consider that middleware use a subset of the nodejs runtime features so to perform http request you have to use the custom server. AIf you want you can then left to the middleware just the set/check of the cookies.

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