The error message "Property '$auth' is not found on Promise type" is prompting an issue with the

I recently configured a new Nuxt.js app with Typescript, but I'm encountering some Typescript errors that seem to be connected to the $auth module. Here is how my tsconfig.json looks in terms of "types" settings:

"types": [
  "@types/node",
  "@nuxt/types",
  "@types/nuxtjs__auth",
  "@nuxtjs/axios",
 ]

Below is the code snippet causing the issue:

      async login() {
        try {
          await this.$auth.loginWith('local', {
            data: {
              user: {
                email: this.email,
                password: this.password
              }
            }
          })

          this.$router.push('/dashboard')
        } catch (e) {
          this.error = e.response.data.message
        }
      }

This is the error message I'm receiving:

Property '$auth' does not exist on type '{ login(): Promise<void>; }'.

I've read several Stack Overflow posts suggesting to add types to the tsconfig.json, which I implemented but it hasn't resolved this particular issue.

Any suggestions on how I can resolve this?

EDIT:

nuxt.config.js

require('dotenv').config()
const axiosUrl = process.env.AXIOS_BASE_URL;
const port = process.env.NODE_ENV === 'production' ? process.env.PORT : 3333;

export default {
  // Disable server-side rendering (https://go.nuxtjs.dev/ssr-mode)
  ssr: true,

  // Global page headers (https://go.nuxtjs.dev/config-head)
  head: {
    title: 'ollie-frontend',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  // Global CSS (https://go.nuxtjs.dev/config-css)
  css: [
  ],

  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
  ],

  // Auto import components (https://go.nuxtjs.dev/config-components)
  components: true,

  // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
  buildModules: [
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
    '@nuxtjs/google-fonts',
    ['@nuxt/typescript-build', {
      typeCheck: true,
      ignoreNotFoundWarnings: true,
    }],
  ],

  // Modules (https://go.nuxtjs.dev/config-modules)
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth'
  ],

  // Build Configuration (https://go.nuxtjs.dev/config-build)
  build: {
  },

  server: {
    port: port,
  },

  axios: {
    baseURL: axiosUrl
  },

  auth: {
    redirect: {
      login: '/sign_in',
      logout: '/',
    },
    strategies: {
      local: {
        endpoints: {
          login: { url: '/login', method: 'post', propertyName: 'token' },
          register: { url: '/signup', method: 'post' },
          user: { url: '/api/v1/users/me', method: 'get', propertyName: 'user' },
          logout: false
        }
      }
    }
  },

  router: {
    middleware: ['auth']
  },

  typescript: {
    typeCheck: {
      eslint: {
        files: './**/*.{ts,js,vue}'
      }
    }
  },
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@types/nuxtjs__auth",
      "@nuxtjs/axios",
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

Answer №1

Your initial export:

export default {
  ssr: true,

  // ...

  typescript: {
    typeCheck: {
      eslint: {
        files: './**/*.{ts,js,vue}'
      }
    }
  },
};

It is recommended to wrap your export with Vue.extend, like this:

export default Vue.extend({
  ssr: true,

  // ...

  typescript: {
    typeCheck: {
      eslint: {
        files: './**/*.{ts,js,vue}'
      }
    }
  },
});

This adjustment will ensure TSC recognizes the correct types when utilizing the object.

(Also, the title may be misleading in comparison to the actual TSC error displayed)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to eliminate Typescript assert during the execution of npm run build?

How can I effectively remove Typescript asserts to ensure that a production build generated through the use of npm run build is free of assertions? Your assistance is appreciated ...

Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js? I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend. Here is my vue application: ...

Uncertain about the best way to utilize an observable

I am currently developing a real-time chat application using Angular and Node.js. The backend is powered by nodejs and I am utilizing socket.io for communication. Server Side io.on('connection', (socket) => { socket.on('new-message&apo ...

Struggling to display blob URL on "pdf-viewer" component with "ng2-pdf-viewer" in Angular version 10

I am facing an issue with an API that returns uploaded files as blobs. When trying to bind the src with a blob URL, nothing is shown. However, if I bind it with a direct URL, the PDF file is displayed successfully. Below is my code snippet. My TypeScript ...

What is the best way to incorporate an assets folder into a Vue component?

After following Vue's official Webpack template, I attempted the following: data () { photoEditorAssets: require('../assets/img/photoeditorsdk/assets'), } mounted () { var editor = new PhotoEditorSDK.UI.DesktopUI({ //eslint-disable-li ...

Generating consistent stack identifiers for multiple stacks within AWS CDK

Is there a way to ensure that when running npx cdk synth in an AWS CDK application consisting of multiple stacks intended for deployment in various environments, the stack names are displayed in a more user-friendly manner? #!/usr/bin/env node import * as ...

Having difficulty accessing a VueJS web application from an AngularJS index.html page

Attempting to combine AngularJS and VueJS projects proved to be a challenging task due to the necessity of invoking the flow designed in VueJS from within an AngularJS application. The process involved including dependencies in the package.json file of bot ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

How to implement the img attribute within a paragraph using Vue.js

One way to achieve this in Laravel is by adding the following code inside the AppServiceProvider: public function boot() { $content = [ '<p>Lorem Ipsum Dolor</p> <p><img src='img/image.jpg'></ ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

Is it possible that CSS is being impacted by DomSanitizer and Renderer2, causing issues with the flow and inheritance of styles?

As I embark on creating my own Calendar with Angular, I am faced with the challenge of utilizing innerHTML while ensuring safety measures are in place. Admittedly, I am new to this and must confess that my code may not be the most elegant. Following tutori ...

Is it possible to acquire Axios Response prior to Vue Component rendering?

I need to utilize: homePage.image = 'storage/' + 'rkiGXBj7KJSOtsR5jiYTvNOajnzo7MlRAoXOXe3V.jpg' within: <div class="home-image" :style="{'background-image': 'url(' + homePage.image + ')'} ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

In Vue3, when using the `script setup` with the `withDefaults` option for a nested object, its attributes are marked as required. How can this issue

I have defined a props object with certain attributes: interface Props { formList: BaseSearchFormListItemType[], inline?: boolean searchBtn?: { show?: boolean text?: string type?: string size?: string } } const props = withDefaults( ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Tips for generating cautionary claims in Playwright TypeScript assessments for non-urgent issues?

Is there a way to implement warnings instead of failures for non-critical assertions in Playwright TypeScript tests? Currently, while working on Playwright tests using TypeScript, I am searching for a solution to handle assertions that would issue warning ...

Executing numerous TypeScript 'tsc' commands

I'm currently working on setting up an NPM command to transpile two separate Typescript projects located in subdirectories within my application, followed by starting the server. Within my 'src' public folder, I have 'Server' and ...

Issues arise when attempting to incorporate the <style> tag in conjunction with requirejs and vue

I've been working on integrating a Vue app with an existing MVC application using require-js, require-vuejs, and vue-js. Everything was going smoothly until I encountered an error when trying to add a <style scoped> tag inside a component. If I ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...