I'm setting up an authentication flow with JWT with my strapi backend and a next.js frontend. Testing the backend with postman works as expected. I get back a user object and a JWT token. But calling my backend from my frontend results in a statuscode 500 - internal server error. I honestly don't see where I'm wrong and I tried to rewrite those calls from scratch again and again. Does anyone see where I have been wrong?
Here's my register.js where the call to my backend happens:
import cookie from 'cookie'
import { API_URL } from '@/config/index'
export default async (req, res) => {
if (req.method === 'POST') {
const { username, email, password } = req.body
const strapiRes = await fetch(`${API_URL}/auth/local/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username,
email,
password,
}),
})
const data = await strapiRes.json()
if (strapiRes.ok) {
// Set Cookie
res.setHeader(
'Set-Cookie',
cookie.serialize('token', data.jwt, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: 60 * 60 * 24 * 7, // 1 week
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} not allowed` })
}
This is my register function in my context
const register = async (user) => {
const res = await fetch(`${NEXT_CLIENT_URL}/api/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(user),
})
const data = await res.json()
if (res.ok) {
setUser(data.user)
router.push('/account/dashboard')
} else {
setError(data.message)
setError(null)
}
}
This is how I call the context function in my next frontend
const handleSubmit = (e) => {
e.preventDefault()
if (password !== password2) {
toast.error('Passwords do not match!')
return
}
register({ username, email, password })
}
Glad for every piece of advice! Logging in works as expected in the same app.