I'm encountering an issue with cookies in my code, but I don't believe it's a simple typo.
Error: TypeError - Cannot read properties of undefined (reading 'signedCookies')
// auth.js
import axios from 'axios'
axios.defaults.withCredentials = true
export const getServerSideToken = (req) => {
const { signedCookies = {} } = req
if (!signedCookies) {
return {}
} else if (!signedCookies.token) {
return {}
}
return { user: signedCookies.token }
}
const WINDOW_USER_SCRIPT_VARIABLE = '__USER__'
export const getUserScript = (user) => {
return `${WINDOW_USER_SCRIPT_VARIABLE} = ${JSON.stringify(user)}`
}
export const loginUser = async (email, password) => {
const { data } = await axios.post('/api/login', { email, password })
if (typeof window !== 'undefined') {
window[WINDOW_USER_SCRIPT_VARIABLE] = data || {}
}
}
export const getUserProfile = async () => {
const { data } = await axios.get('/api/profile')
return data
}
The error seems to be originating here and I am unsure about the cause
> 6 | const { signedCookies = {} } = req
| ^
7 |
8 | if (!signedCookies) {
9 | return {}
I'm using this auth.js file in a _document.js file :
//_document.js
import Document, { Head, Main, NextScript } from 'next/document'
import { getServerSideToken, getUserScript } from '../lib/auth'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const props = await Document.getInitialProps(ctx)
const userData = await getServerSideToken(ctx.req)
return { ...props, ...userData }
}
render() {
const { user = {} } = this.props
return (
<html>
<Head />
<body>
<Main />
<script dangerouslySetInnerHTML={{ __html: getUserScript(user) }} />
<NextScript />
</body>
</html>
)
}
}
Any help would be greatly appreciated!