简体   繁体   中英

Next.js SSR store access token without using redux

I've implemented a server-side rendering application using NextJS and ReactJS.

When the user login into the application, I want to store some of the user details like access token, refresh token, email address and use it throughout the application. (Kind of storing it globally like how we use local storage on Client side rendering applications)

I'm not using REDUX, so I would like to know the best way of storing those user details without making use of REDUX.

What are the different ways to achieve this while working with SSR?

I'd recommend to use a session cookie. This is available in next.js getInitialProps method.

static async getInitialProps ({req}) {
  console.log(req.headers.cookies) // depending on your server middlewares / config, this is available
}

LocalStorage or SessionStorage is not available in SSR, whereas the cookies are always attached to the request. I'd further recommend to make the cookie secure (only served via https) and protect from JS client / browser access with http-only .

When using express-session using cookies/sessions gets more convenient.

static async getInitialProps ({req}) {
  console.log(req.session) // with express session
}
> import cookie from 'cookie'
> 
> export function parseCookies(req) {   return cookie.parse(req ?
> req.headers.cookie || "" : document.cookie); }

I recently worked on something similar. Typically, you can store it in storage or cookies. But with nextJS , you would want to make use of it in both client and server side methods such as getServerSideProps . That way you can early detect if user is logged in, make API calls before page is rendered (making use of nextJS SSR).

Refer this discussion which clearly mentions that cookie is the way. This is what the collaborator at NextJS says:

If you want to have data available on both the client and server you could use cookies.

This makes sense. Remember , your methods like getServerSideProps do not run on the client and do not have access to these objects : document , window etc..

When login is done in client you can set cookie like : document.cookie = "cookiename=hello" . Here is an SO answer

In getServerSideProps(context), make use of the param context, it gives you access to the request like context.req . Then you can get cookie from the request object, using a cookie parser module or context.req.headers.cookie .

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