Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

requireUserSession Returns undefined for Secure User ID in Internal API Request #374

Open
tahirmahmudzade opened this issue Mar 15, 2025 · 1 comment

Comments

@tahirmahmudzade
Copy link

tahirmahmudzade commented Mar 15, 2025

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?

@endorfin
Copy link

endorfin commented Apr 4, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants