Description
In my Nuxt application, I am making an internal server-side fetch request from one API route to another using $fetch In-Server fetch. The API being called /api/collectionItems
uses requireUserSession(event) to retrieve the authenticated user’s secure ID. However, despite having a valid session in the initial request, requireUserSession(event) returns undefined, leading to a 401 Unauthorized error.
Requesting API (index.ts)
export default catchEventHandler(async (event) => {
const paramId = getRouterParam(event, 'id')
if (!paramId) {
throw createError({ statusCode: 400, message: 'Invalid id' })
}
const { data, success, error } = await readValidatedBody(event, CreateCollectionItemsSchema.safeParse)
if (!data || !success) {
console.log('Error creating items:', error)
throw createError({ statusCode: 400, message: formatZodError(error) })
}
await $fetch('/api/collectionItems', { method: 'POST', body: data })
return { statusCode: 201, message: `Collection items updated successfully` }
})
collectionItem.post.ts
export default catchEventHandler(async event => {
const { secure } = await requireUserSession(event) // Secure user ID is undefined
await createCollectionItems(data, secure.userId)
return { statusCode: 201, message: `Collection items created successfully` }
})
Expected Behavior
- The session information, including secure.userId, should persist when making the internal request.
- requireUserSession(event) should return the authenticated user’s ID in collectionItem.post.ts.
Actual Behavior
-
secure.userId is undefined inside collectionItem.post.ts, causing a 401 Unauthorized error.
-
Should I explicitly forward session cookies when making the internal $fetch request?
-
Does requireUserSession require additional configuration for in-server API calls?
-
Is there a recommended approach to persist authentication across internal fetch requests?