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

#imports has no exported member named 'setUserSession'. Did you mean 'useUserSession'?

Open olada opened this issue 10 months ago • 3 comments

Hello,

I have been following the basic recipe regarding sessions and authentication on nuxt.com.

In our project set up, we favor making imports explicit which is why autoImports are disabled. Therefore we resolve auto-imported dependency using import { ... } from '#imports'.

In the case of the login api endpoint this means that I want to resolve setUserSession using import { setUserSession } from '#imports';.

This has led to following error message:

server/api/login.ts:6:10 - error TS2724: '"#imports"' has no exported member named 'setUserSession'. Did you mean 'useUserSession'?

6 import { setUserSession } from '#imports';
           ~~~~~~~~~~~~~~


Found 1 error in server/api/login.ts:6


 ERROR  Process exited with non-zero status (2)                                                                                                                                                         22:04:28

    at R._waitForOutput (/C:/Users/e095514/AppData/Local/pnpm-cache/dlx/pf4f5e55jqd5qamuwuqglrr6jm/194bdfbc173-6938/node_modules/.pnpm/[email protected]/node_modules/nuxi/dist/chunks/main.mjs:508:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.run (/C:/Users/e095514/AppData/Local/pnpm-cache/dlx/pf4f5e55jqd5qamuwuqglrr6jm/194bdfbc173-6938/node_modules/.pnpm/[email protected]/node_modules/nuxi/dist/chunks/typecheck.mjs:64:7)
    at async runCommand$1 (/C:/Users/e095514/AppData/Local/pnpm-cache/dlx/pf4f5e55jqd5qamuwuqglrr6jm/194bdfbc173-6938/node_modules/.pnpm/[email protected]/node_modules/nuxi/dist/shared/nuxi.VcyMLvO6.mjs:1767:16)
    at async runCommand$1 (/C:/Users/e095514/AppData/Local/pnpm-cache/dlx/pf4f5e55jqd5qamuwuqglrr6jm/194bdfbc173-6938/node_modules/.pnpm/[email protected]/node_modules/nuxi/dist/shared/nuxi.VcyMLvO6.mjs:1758:11)
    at async runMain$1 (/C:/Users/e095514/AppData/Local/pnpm-cache/dlx/pf4f5e55jqd5qamuwuqglrr6jm/194bdfbc173-6938/node_modules/.pnpm/[email protected]/node_modules/nuxi/dist/shared/nuxi.VcyMLvO6.mjs:1896:7)

More readable screenshot:

Image

After losing way too much time, I figured that I can have tsc ignore the error - but this does not seem to be a good solution. Since the error suggests to use useUserSession, it seems that non-server-imports are detected just fine but there is an issue regarding serverImports. I find this odd because when I take a look at ~/.nuxt/types/nitro-imports.ts, I can see a line which contains setUserSession and other exports:

export { sessionHooks, getUserSession, setUserSession, replaceUserSession, clearUserSession, requireUserSession } from '../../../node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/nuxt-auth-utils/dist/runtime/server/utils/session';

Is this sort of behavior normal? Can you tell me the reason why the server imports cannot be resolved? Is this an issue with my setup? Is this a bug in the module or even in nuxt?

Thanks very much in advance and kind regards, David

PS: Output of pnpx nuxi info:



olada avatar Jan 31 '25 21:01 olada

Would you mind sharing a minimal reproduction so I can dig into it? 🙏

atinux avatar Feb 05 '25 09:02 atinux

I have the same issue i think.

i have this server utility: server/utils/api.ts

import { $fetch, type FetchOptions } from 'ofetch'
import type { H3Event } from 'h3'
import type { UserSession  } from '#auth-utils'
import {  useRuntimeConfig } from '#imports'

/**
 * A universal server/client fetch utility that:
 *  - Retrieves the user session from nuxt-auth-utils
 *  - Extracts `session.secure.access_token` if present
 *  - Adds `Authorization: Bearer <token>`
 *  - Optionally uses a baseURL from runtime config (or you can hardcode one)
 * 
 * @param url The endpoint path (can be full or relative)
 * @param options Additional fetch options (method, body, headers, etc.)
 * @param event An optional H3Event (if calling from a server endpoint). 
 */
export async function easyApiFetch<T = unknown> (
  url: string,
  options: FetchOptions = {},
  event?: H3Event | null,
  _session?:  UserSession  
): Promise<T> {
  const session  = event ?  await getUserSession(event) : _session
  const token = session?.secure?.access_token

  const headers = {
    ...(options.headers || {}) as Record<string, string>
  }
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }


  const config = useRuntimeConfig()
  const baseURL = config.public?.apiUrl || 'https://api.example.com'

  return await $fetch<T>(url, {
    ...options,
    baseURL,
    headers
  })
}

It is used in this middleware:

import { easyApiFetch } from "~/server/utils/api";
export default defineNuxtRouteMiddleware(async () => {
  const nuxtApp = useNuxtApp()
  const event = nuxtApp.ssrContext?.event
  const { loggedIn, } = useUserSession();
  if (loggedIn) {
    const handler = await easyApiFetch("/v1/user", {
      method: "GET",
    },event);
    console.log('response',handler)
  }

  if (!loggedIn.value) {
    return navigateTo("/auth/login");
  }
});

I am getting this error:

500
getUserSession is not defined

at ./middleware/auth.ts:12:123

getUserSession is perfectly accessible from server/api/somefunction.ts but not from server/utils/api.ts

Nuxt Config:

export default defineNuxtConfig({
  compatibilityDate: "2024-11-01",
  devtools: { enabled: true },
  nitro:{
    imports:{
      dirs: [
        'server/utils/**'
      ]
    }
  },

MathiasOdlund avatar Feb 26 '25 12:02 MathiasOdlund

I'm having same issue, I think it appeared after installing some packages. Anyone found a fix?

arshx86 avatar Oct 27 '25 21:10 arshx86