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

Cannot find module '#auth' or its corresponding type declarations. TS error #418

Open
KitsuneKenshi opened this issue May 31, 2023 · 16 comments
Assignees
Labels
documentation A change to the documentation p2 Nice to have provider-authjs An issue with the authjs provider

Comments

@KitsuneKenshi
Copy link

KitsuneKenshi commented May 31, 2023

Environment

------------------------------
- Operating System: Windows_NT
- Node Version:     v18.16.0
- Nuxt Version:     3.5.2
- Nitro Version:    2.4.1
- Package Manager:  pnpm@8.5.1
- Builder:          vite
- User Config:      modules, auth
- Runtime Modules:  @sidebase/nuxt-auth@0.6.0-beta.2
- Build Modules:    -
------------------------------

Reproduction

Getting this error is as simple as just pasting import { NuxtAuthHandler } from '#auth' into [...].ts file in server/api/auth directory.

Describe the bug

It seems like TS can't find declaration for this module.
image

Additional context

I made sure it's not just an issue on my side, and tried it on 3 different machines (2 PCs and 1 VM) with Volar in takeover mode, as recommended by Nuxt, and still got the same results. I've tried to replicated this issue on Blitz, but failed in doing so. Here's link to repo: https://github.com/KitsuneKenshi/nuxt-auth-ts-error

Logs

No response

@purefunctor
Copy link

purefunctor commented Jun 3, 2023

I've tracked this down to be a problem w/ having a tsconfig.json file inside of the server directory, which goes like the following:

{
  "extends": "../.nuxt/tsconfig.server.json",
}

tsconfig.server.json is generated as follows:

{
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowJs": true,
    "resolveJsonModule": true,
    "paths": {}
  },
  "include": [
    "./types/nitro.d.ts",
    "../**/*",
    "../server/**/*"
  ]
}

Ideally, "./types/auth.d.ts" should be in include. Removing said tsconfig.json works--rewriting the include to be something like the following works too:

{
  "extends": "../.nuxt/tsconfig.server.json",
  "include": [
    ".nuxt/types/auth.d.ts",
    ".nuxt/types/nitro.d.ts",
    "./server/**/*"
  ]
}

Alternatively:

import { promises as fsp } from "node:fs";
import { resolve } from "path"

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
    pages: true,
    modules: [
        '@nuxtjs/tailwindcss',
        '@sidebase/nuxt-auth',
        async (_, nuxt) => {
            nuxt.hook("nitro:init", (nitro) => {
                nitro.hooks.hook("compiled", async () => {
                    const tsconfigPath = resolve(nitro.options.buildDir, nitro.options.typescript.tsconfigPath);
                    const tsconfig = JSON.parse(await fsp.readFile(tsconfigPath, "utf8"));
                    tsconfig.include.push("./types/auth.d.ts");
                    await fsp.writeFile(tsconfigPath, JSON.stringify(tsconfig, null, 2));
                })
            });
        }
    ]
})

Maybe we can integrate the latter?

Relevant: unjs/nitro#1266

@KitsuneKenshi
Copy link
Author

KitsuneKenshi commented Jun 3, 2023

@purefunctor thanks for providing work-around for this issue, but now it doesn't update types for custom data in session.
Do you have any possible solutions for that?

EDIT:
Figured it out myself. I didn't check next-auth docs. Everything works now.

@revandpratama
Copy link

@purefunctor thanks for providing work-around for this issue, but now it doesn't update types for custom data in session. Do you have any possible solutions for that?

EDIT: Figured it out myself. I didn't check next-auth docs. Everything works now.

Could you elaborate? Im having the same problem

@KitsuneKenshi
Copy link
Author

@revandpratama Check this

@FollowJack
Copy link

Please more instructions on this one.

@KitsuneKenshi
Copy link
Author

@FollowJack basically what you have to do is create a file in the types folder, called next-auth.d.ts.
Inside this file, you can make something like this:

import NextAuth, { DefaultSession } from "next-auth"

declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
/** The user's postal address. */
address: string
} & DefaultSession["user"]
}
}

Address is an example value, and you should change it, to what you need inside user type.
At least that's what I did, and it worked.

@JeremyQtweb
Copy link

I had this issue out of the gate until I threw caution to the wind and built my project anyway... and since then it finds #auth. Same thing happened with the auth: property in nuxt.config... couldn't be found until the project was built the first time.

@semkeijsper
Copy link

semkeijsper commented Jun 12, 2023

I got it to work using the following tsconfig.json:

{
  "extends": "../.nuxt/tsconfig.server.json",
  "include": [
    "../.nuxt/types/nitro.d.ts",
    "../.nuxt/types/auth.d.ts",
    "../server/**/*"
  ]
}

@gertjanjansen
Copy link

gertjanjansen commented Jul 5, 2023

I got it to work using the following tsconfig.json:

{
  "extends": "../.nuxt/tsconfig.server.json",
  "include": [
    "../.nuxt/types/nitro.d.ts",
    "../.nuxt/types/auth.d.ts",
    "../server/**/*"
  ]
}

This seems to solve the issue for me, but only partially. My types are recognized correctly in VSCode by applying this, but when running nuxt dev I now run into this:

[nitro] [uncaughtException] Error: RuntimeError: Type must match at this point                                                                         8:18:55 PM
    at useTypedBackendConfig (file:///Users/gertjan/Sites/nuxt_tryout/.nuxt/dev/index.mjs:855:9)
    at useConfig (file:///Users/gertjan/Sites/nuxt_tryout/.nuxt/dev/index.mjs:902:25)
    at NuxtAuthHandler (file:///Users/gertjan/Sites/nuxt_tryout/.nuxt/dev/index.mjs:934:16)
    at file:///Users/gertjan/Sites/nuxt_tryout/.nuxt/dev/index.mjs:997:15
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Any suggestions?

(Edit: hmm.. it looks like it's a different issue than the typing issue. I'll investigate a bit more tomorrow.)

@gertjanjansen
Copy link

Well, it seems my typing issue has been resolved now. What I learned from this is that switching from the local to authjs provider changes the types being used, which is not always picked up by VSCode, or leads to stuff being out of sync when there's something being cached somewhere.

I also don't completely understand the approach of having two different "providers", that lead to different types in build time and runtime. I'm not an expert on nuxt plugins (yet), so maybe that's just me.
It also took me a while to figure out that the authjs "provider" itself also has it's own "providers", meaning there are two different levels of providers.

@zoey-kaiser
Copy link
Member

Hi @gertjanjansen,

We know that having two providers is not optimal, however we decided to introduce our own, as we had little to no control over how authjs handeled their systems. For example: We wanted to use static generation on one of our projects, something not supported by authjs, which is why we created our own local provider over which we have full control!

I personally have no issues with VSCode detecting types, however this is different for every person. If you run into more issues, have a look here: https://sidebase.io/sidebase/resources/coding-setup

We detail how we setup our machines internally. Maybe it helps!

@zoey-kaiser zoey-kaiser closed this as not planned Won't fix, can't repro, duplicate, stale Nov 6, 2023
@rowphant
Copy link

rowphant commented Dec 5, 2023

Hi!
I still dont get it. It tried everything what is suggested in this thread but nothing works.
To be honest Im wondering about the '#auth' import. Never seen something like this before. When I was switching from React to Vue I thought it would get easier to handle authentication and sessions but with Vue.js it just seems to get much more complicated. :(
Now the thread is closed but there is still no proper solution...or im just too stupid to find it. Can anybody help?

@zoey-kaiser zoey-kaiser reopened this Dec 6, 2023
@zoey-kaiser
Copy link
Member

Hi @rowphant, I only closed the issue, as there was less activity on it! I would love to help you further:

#auth import is a "virtual" import from Nuxt. Normally inside your application you would not even need to import the composable with a typical import statement and they should be available right away. On the server end you will need to import it like this.

I would summarize everything said before this with the following steps:

If all of these steps have not resolved your issue, I am going to need some kind of minimal replication of your project, where I can look into why the types are not working correctly.

Also: I see this was your first message in this thread, what exactly is the issue you are currently facing? I have been trying to deduct it from your "thumbs up/thumbs down" reactions, but its a bit hard 😓

I would love to help you out and improve your Nuxt experience!

@wavedeck
Copy link

wavedeck commented Feb 8, 2024

To add to this, i had the same issue that #auth wasn't recognised by typescript even though i've implemented the workaround

In my case, the solution was even more stupid.. just regenerate the .nuxt directory and clear all caches with the nuxi cleanup command and then starting the dev server again.

Granted, my environment is:

------------------------------
- Operating System: Darwin
- Node Version:     v21.6.1
- Nuxt Version:     3.10.1
- CLI Version:      3.10.0
- Nitro Version:    2.8.1
- Package Manager:  pnpm@8.15.1
- Builder:          -
- User Config:      devtools, modules, auth
- Runtime Modules:  @sidebase/nuxt-auth@0.6.7
- Build Modules:    -

Additionally:
- Jetbrains Webstorm IDE: 2023.3.3
------------------------------

@zoey-kaiser zoey-kaiser removed the bug label Feb 23, 2024
@zoey-kaiser
Copy link
Member

Hello everyone 👋

Due to my current cleanup of all issue I will propose the following steps to resolve this issue:

  • We add a new documentation section for setting up NuxtAuth with Typescript
  • We include docs for:
    • Resolving this issue
    • Adjusting the SessionData type.

I think this should help people in the future not struggle with the same issue.

@zoey-kaiser zoey-kaiser added documentation A change to the documentation p2 Nice to have provider-authjs An issue with the authjs provider labels Feb 23, 2024
@zoey-kaiser zoey-kaiser self-assigned this Feb 23, 2024
@phoenix-ru
Copy link
Collaborator

Related to #596

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation A change to the documentation p2 Nice to have provider-authjs An issue with the authjs provider
Projects
None yet
Development

No branches or pull requests