TypeScript Integration
Learn about TypeScript integration in Nuxt Umbu, including auto-generated types, type-safe composables, and IDE autocomplete support.
Overview
Nuxt Umbu provides full TypeScript support with automatic type generation, ensuring type safety and excellent IDE autocomplete throughout your application.
Automatic Type Generation
Nuxt Umbu automatically generates TypeScript types during the build process using the prepare:types hook. This ensures:
- Full type safety for auth methods
- IDE autocomplete for all auth functionality
- Type checking at compile time
- Provider-specific type definitions
Generated Types Location
Types are generated in .nuxt/types/umbu.d.ts and include:
AuthInstanceinterface with all auth methods- Provider-specific type definitions
- Configuration option types
- State management types
AuthInstance Interface
The main AuthInstance interface provides type-safe access to authentication functionality:
export interface AuthInstance {
$headers: Headers
readonly _prefix: string
readonly options: ModuleOptions
readonly state: AuthState
// Properties
get user(): Record<string, unknown> | null
get strategy(): string | null
get loggedIn(): boolean
get headers(): Headers
get prefix(): string | null
// Methods
set headers(headers: Headers)
getRedirect(strategyName: string): Record<string, unknown> | null
csrfToken(event?: H3Event): Promise<boolean>
initialize(): Promise<void>
loginWith(strategyName: string, value: Record<string, unknown>): Promise<Record<string, unknown>>
logout(strategyName: string): Promise<void>
twoFactor(strategyName: string, code: string): Promise<{ success: boolean }>
}
Using Types in Your Application
Accessing Auth Instance with Types
const { $auth } = useNuxtApp()
// Full autocomplete and type checking
const user = $auth.user
const isLoggedIn = $auth.loggedIn
const currentStrategy = $auth.strategy
// Type-safe method calls
await $auth.loginWith('password', {
username: 'user@example.com',
password: 'secret'
})
Type-Safe Composables
Composables are fully typed:
import { useAuthStore } from '#auth-utils'
const authStore = useAuthStore()
// Type-safe state access
const user = authStore.user
const token = authStore.token
const strategy = authStore.strategy
// Type-safe methods
await authStore.fetchUser()
await authStore.setToken('new-token')
Provider-Specific Types
Sanctum Types
import type { SanctumModuleOptions, SanctumStrategiesOptions } from '#auth-types'
const config: SanctumModuleOptions = {
provider: 'sanctum',
csrf: '/sanctum/csrf-cookie',
strategies: {
default: {
endpoints: {
login: { url: '/login', method: 'post' },
user: { url: '/api/user', method: 'get' }
},
redirect: {
login: '/login',
logout: '/'
}
}
}
}
Passport Types
import type {
PassportModuleOptions,
PassportStrategiesOptions,
AuthSecretConfig
} from '#auth-types'
const config: PassportModuleOptions = {
provider: 'passport',
strategies: {
password: {
endpoints: {
login: { url: '/oauth/token', method: 'post' },
user: { url: '/api/user', method: 'get' }
},
redirect: {
login: '/login',
logout: '/'
}
}
}
}
const secret: AuthSecretConfig = {
client_id: 'your-client-id',
client_secret: 'your-client-secret',
grant_type: 'password'
}
Configuration Types
Module Options
import type { ModuleOptions } from '#auth-types'
const authConfig: ModuleOptions = {
provider: 'sanctum',
cookie: {
prefix: 'auth.',
options: {
httpOnly: false,
secure: false,
sameSite: 'Lax'
}
},
strategies: {
default: {
endpoints: {
login: { url: '/login', method: 'post' },
user: { url: '/api/user', method: 'get' }
},
redirect: {
login: '/login',
logout: '/'
}
}
}
}
Cookie Options
import type { CookieOption, AuthOptionsCookie } from '#auth-types'
const cookieOptions: CookieOption = {
httpOnly: true,
secure: true,
sameSite: 'Strict',
priority: 'high',
maxAge: 60 * 60 * 24 * 7
}
const authCookie: AuthOptionsCookie = {
prefix: '__Secure-',
options: cookieOptions
}
Redirect Options
import type { RedirectOptions } from '#auth-types'
const redirectOptions: RedirectOptions = {
login: '/login',
logout: '/',
home: '/dashboard',
twoFactor: '/2fa',
callback: '/auth/callback'
}
Type-Safe Custom Hooks
Create type-safe custom hooks using Nuxt Umbu types:
import type { AuthInstance } from '#auth-types'
export function useCustomAuth() {
const { $auth } = useNuxtApp()
const auth = $auth as AuthInstance
const login = async (credentials: { email: string; password: string }) => {
return await auth.loginWith('password', credentials)
}
const logout = async () => {
await auth.logout('password')
}
const checkAuth = () => {
return auth.loggedIn
}
return {
login,
logout,
checkAuth,
user: computed(() => auth.user),
isLoggedIn: computed(() => auth.loggedIn)
}
}
Type Guards
Use type guards for runtime type checking:
import type { ModuleOptions, PassportModuleOptions, SanctumModuleOptions } from '#auth-types'
function isPassportConfig(config: ModuleOptions): config is PassportModuleOptions {
return config.provider === 'passport'
}
function isSanctumConfig(config: ModuleOptions): config is SanctumModuleOptions {
return config.provider === 'sanctum'
}
// Usage
const config = useRuntimeConfig().public.auth as ModuleOptions
if (isPassportConfig(config)) {
// TypeScript knows this is PassportModuleOptions
console.log('Using Passport provider')
} else if (isSanctumConfig(config)) {
// TypeScript knows this is SanctumModuleOptions
console.log('Using Sanctum provider')
}
Generic Types
Create generic functions with auth types:
import type { AuthInstance, ModuleOptions } from '#auth-types'
async function loginWithStrategy<T extends keyof ModuleOptions['strategies']>(
auth: AuthInstance,
strategy: T,
credentials: Record<string, unknown>
) {
return await auth.loginWith(strategy as string, credentials)
}
// Usage
await loginWithStrategy($auth, 'password', {
username: 'user@example.com',
password: 'secret'
})
Extending Types
You can extend Nuxt Umbu types for your application:
// types/auth.d.ts
import type { AuthInstance } from '#auth-types'
declare module '#auth-types' {
interface AuthInstance {
customMethod(): Promise<void>
}
}
// Implementation
const { $auth } = useNuxtApp()
$auth.customMethod() // Now typed
Type-Safe API Calls
Combine auth types with API calls:
import type { AuthInstance } from '#auth-types'
async function fetchProtectedData(auth: AuthInstance) {
if (!auth.loggedIn) {
throw new Error('Not authenticated')
}
const headers = auth.headers
const response = await $fetch('/api/protected', {
headers: Object.fromEntries(headers.entries())
})
return response
}
IDE Autocomplete
VS Code
VS Code provides full autocomplete for Nuxt Umbu:
- Install the official Vue extension
- Ensure TypeScript is enabled
- Restart VS Code after configuration changes
- Types are automatically loaded from
.nuxt/types/umbu.d.ts
WebStorm
WebStorm also supports Nuxt Umbu types:
- Enable TypeScript in project settings
- Ensure node_modules are properly indexed
- Use "Invalidate Caches" if types don't appear
- Types are automatically recognized
Type Checking in CI
Add type checking to your CI pipeline:
{
"scripts": {
"typecheck": "nuxt typecheck"
}
}
# .github/workflows/ci.yml
- name: Type check
run: pnpm typecheck
Common Type Issues
Types Not Recognized
If types aren't recognized:
- Restart your IDE
- Delete
.nuxtfolder and rebuild - Ensure TypeScript is enabled in your project
- Check that
@nuxt/kitis properly installed
Type Errors After Updates
If you get type errors after updates:
- Clear
.nuxtfolder:rm -rf .nuxt - Reinstall dependencies:
pnpm install - Restart dev server:
pnpm dev - Check for breaking changes in changelog
Missing Autocomplete
If autocomplete doesn't work:
- Verify TypeScript language service is running
- Check that
umbu.d.tsexists in.nuxt/types/ - Ensure your IDE supports TypeScript
- Try restarting the TypeScript server
Best Practices
- Always use types from
#auth-typesfor type safety - Leverage IDE autocomplete for faster development
- Add type checking to your CI pipeline
- Use type guards for runtime type checking
- Extend types when adding custom auth methods
- Keep type definitions updated with configuration changes
- Use generic types for reusable auth functions
- Document custom type extensions for your team
Troubleshooting
Generated Types Outdated
If generated types seem outdated:
# Clear Nuxt cache
rm -rf .nuxt
# Restart dev server
pnpm dev
Type Conflicts
If you have type conflicts:
// Use type assertions carefully
import type { AuthInstance } from '#auth-types'
const auth = $auth as AuthInstance
Missing Provider Types
If provider-specific types are missing:
- Verify provider is correctly configured
- Check that
prepare:typeshook ran successfully - Ensure provider templates are available
- Rebuild the project
Type Safety Benefits
Using TypeScript with Nuxt Umbu provides:
- Compile-time error detection: Catch errors before runtime
- Better IDE support: Full autocomplete and documentation
- Refactoring confidence: Safe code changes
- Self-documenting code: Types serve as documentation
- Team collaboration: Clear contracts between components
- Reduced testing: Type system catches many bugs