简体   繁体   中英

How to get cookies in getServerSideProps NextJS

In my User page I'm using getServerSideProps to get user's data.

At console.log number 1 you can see that cookies with tokens are exsists. But at console.log number 2 cookies are empty

Also I did same request inside useEffect And it works as I expect. And at the console.log number 2 cookies object contains tokens.

How to set cookies for getServerSideProps request?

 export async function getServerSideProps({req, res}) { console.log(1, req.cookies) const response = await $api.get(`/store/profile/user`, {withCredentials: true}) return { props: {} } } const User: NextPage = ({props}) => { const getData = async () => { const response = await $api.get(`/store/profile/user`, {withCredentials: true}) } React.useEffect(() => { getData() }, []) return ( <LoginLayout> <ProfileLayout> <UserInfo /> </ProfileLayout> </LoginLayout> ) } export default User

 export default async function refresh(req, res, next) { try { console.log(2, req.cookies) const {refreshToken} = req.cookies const userData = await userService.refresh(refreshToken) res.cookie("refreshToken", userData.refreshToken, {maxAge: 5 * 24 * 60 * 60 * 1000, httpOnly: true}) return res.json(userData) } catch (e) { res.status(e.status).json({message: e.message}) } }

logs for getServerSideProps request:

 1 { refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InpoZW4uYWxleGVlZmZAZ21haWwuY29t', token:'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InpoZW4uYWxleGVlZmZAZ21haWwuY29tIiThm' } 2 {}

logs for request inside useEffect:

 2 { refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InpoZW4uYWxleGVlZmZAZ21haWwuY29ih', token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InpoZW4uYWxleGVlZmZAZ21haWwuY29tIiwiaWQg' }

First install cookie package using npm

npm install cookie

and then import it where you need it

import cookie from "cookie";

and the rest must be something like the following:

export const getServerSideProps = async (context) => {
  const mycookie = cookie.parse(
    (context.req && context.req.headers.cookie) || ""
  );

  let cookieNameData = {};
  if (mycookie.whatevercookienameis) {
    cookieNameData = mycookie.whatevercookienameis;
  }

  return { 
    props: {
      cookieNameData
    } 
  }
}

Hope it gives you a clear picture how to achieve it.

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