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.