nuxt-auth-utils icon indicating copy to clipboard operation
nuxt-auth-utils copied to clipboard

requireUserSession Returns undefined for Secure User ID in Internal API Request

Open tahirmahmudzade opened this issue 10 months ago • 2 comments

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?

tahirmahmudzade avatar Mar 15 '25 20:03 tahirmahmudzade

Try event.$fetch for forwarding context and headers https://nuxt.com/docs/guide/directory-structure/server#forwarding-context-headers

endorfin avatar Apr 04 '25 18:04 endorfin

Try event.$fetch for forwarding context and headers https://nuxt.com/docs/guide/directory-structure/server#forwarding-context-headers

The should indeed forward the session cookie - but there are issues if you have updated the session though, as mentioned in #357 and/or #314

DavidDeSloovere avatar Sep 19 '25 13:09 DavidDeSloovere