1

I am using Next JS API routes to make requests to Google API for authentication. Everything works well but I can't seem to get the cookies to be set in the header and I am also unable to read them via context in getServersideProps(context).

I am also making use of the cookie package to set the cookies in the header of the response.

Here is my code in my api/google/auth:

import cookie from 'cookie'

const googleAuthHandler = async (req, res) => {
  if (req.method !== 'GET') {
    res.status(405).send({ message: 'Only GET requests allowed' })
    return
  }
  const { code } = req.query;

  try {
    const resData = await fetch(
      `${process.env.NEXT_PUBLIC_EXTERNAL_API_URL}?code=${code}`,
    ).then((response) => response.text()).then(result => JSON.parse(result).data);

    if(!resData) {
      res.status(400).send({ message: 'No data returned' })
      return
    }

    // Access Token
    const {
      accessToken
    } = resData;

    // Set cookie in header
    res
      .status(200)
      .setHeader(
        'Set-Cookie', 
        cookie.serialize('token', accessToken, {
          path: "/",
          httpOnly: true,
          secure: process.env.NODE_ENV !== 'development',
          maxAge: 60 * 60 * 24 * 7 // 1 week
        })
      )
      .json({ data: resData });

  } catch (error) {
    res.status(500).send('Error connecting to server!');
    console.error(error)
  }
};

export default googleAuthHandler;

Here is my code to read the cookie in my dashboard page:

import cookie from 'cookie'

export async function getServerSideProps(context) {
  const { req } = context;
  const cookies = cookie.parse(req.headers.cookie || '');

  const token = cookies.token;
  console.log(token);   //This returns undefined

  return {
    props: {},
  }
}

Weird enough, logging console.log(req.headers.cookie) logs all the data I get from the console in an unusable manner```.

How can I fix this and how do I read the cookie in the header? Thank you in advance.

Idris
  • 558
  • 7
  • 29
  • 1
    What does `context.req.cookies` return inside `getServerSideProps`? Can you see the `token` there? – juliomalves Mar 27 '22 at 16:24
  • 1
    @juliomalves Surprisingly, it returned an object containing the user object and the token itself. I am surprised as to why it's returning the user object as `[[object Object]` when I didn't set it as header. – Idris Mar 27 '22 at 18:19
  • 1
    Could've been an old cookie you had set previously. Does using `context.req.cookies` solve the issue you were having then? – juliomalves Mar 27 '22 at 18:21
  • 1
    @juliomalves, It solves the issue. Thanks – Idris Mar 27 '22 at 18:24

0 Answers0