Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions.
In this component, I am trying to fetch user data from my Strapi backend.
import React from 'react'
import Layout from '../components/Layout'
import { parseCookies } from '@/helpers/index'
import { API_URL } from '../../config'
const Dashboard = ({ events }) => {
return (
<Layout title='User Dashboard'>
<h1>Your events</h1>
{events && events.length && events.map((el, i) => <div>{el.name}</div>)}
</Layout>
)
}
export default Dashboard
export async function getServerSideProps({ req }) {
const { token } = parseCookies(req)
const res = await fetch(`${API_URL}/events/me`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
})
const events = await res.json()
return {
props: {
events
}
}
}
The helper method is supposed to extract the cookie from the request and return the token to getServerSideProps.
import cookie from 'cookie'
export function parseCookies(req) {
console.log('///// REQ IN HELPER', cookie.parse(req.headers.cookie))
return cookie.parse(req ? req.headers.cookie || '' : '')
}
However, instead of returning a token, the method returns the following:
{
_xsrf: '2|07438526|dd1d3c86869ab7209b159b127acbead9|1629292796',
'username-localhost-8888': '2|1:0|10:1629300070|23:username-localhost-8888|44:OThhNzc0YWY=...
}
Here is how I set the cookie after login:
import { API_URL } from '../../config/index'
import cookie from 'cookie'
export default async (req, res) => {
if (req.method === 'POST') {
const { identifier, password } = req.body
const strapiRes = await fetch(`${API_URL}/auth/local`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ identifier, password })
})
const data = await strapiRes.json()
if (strapiRes.ok) {
res.setHeader('Set-Cookie',
cookie.serialize('token', data.jwt),
{
httpOnly: true,
maxAge: 60 * 60 * 24 * 7,
sameSite: 'strict',
path: '/'
})
res.status(200).json({ user: data.user })
} else {
res.status(data.statusCode).json({ message: data.message[0].messages[0].message })
}
}
else {
res.setHeader('Allow', ['POST'])
res.status(405).json({ message: `Method ${req.method} is not allowed` })
}
}
I believe the issue with getting an undefined cookie in the dashboard component might be due to server-side storage settings. Can anyone provide insights on how to resolve this?