@thespielplatz/nuxt-auth
v1.1.0
Published
DB agnostic authentication module for Nuxt based on jwt
Readme
@thespielplatz/nuxt-auth
A simple, database-agnostic authentication module for Nuxt, using JWT for access tokens (in the authorization header) and refresh tokens (stored in cookies).
Features
- Database-agnostic design
- Secure token management: Refresh tokens in cookies & access tokens in headers
Quick Setup
1. Install the package
npm i -D @thespielplatz/nuxt-auth2. Add the module to your nuxt.config.ts
export default defineNuxtConfig({
modules: ['@thespielplatz/nuxt-auth']
})Usage
1. Server
Implement & Register an IUserProvider
The auth module requires an IUserProvider implementation, which can be set using useUserProvider().set(...). For reference, see the playground implementation.
Protect API Routes with defineLoggedInEventHandler
The defineLoggedInEventHandler((event, user) => {}) function ensures only authenticated users can access certain routes. The user object, retrieved from IUserProvider, is passed to the handler. For an example, see the playground implementation.
2. Frontend
All authentication-related features are accessible via $auth in useNuxtApp().
<script setup lang="ts">
const { $auth } = useNuxtApp()The auth module automatically sends a refresh request to the server to verify the login state. Ensure this process is completed before making any server API calls.
Check Login State
onMounted(async () => {
const isLoggedIn = await $auth.isLoggedIn()
})Redirect if Logged In
onMounted(async () => {
await $auth.redirectIfLoggedIn()
})- No need to manually call
$auth.isLoggedIn()if this redirection is used. - Configure the login redirection path in module variables (default:
/dashboard).
Redirect if Logged Out
onMounted(async () => {
await $auth.redirectIfLoggedOut()
})- No need to manually call
$auth.isLoggedIn()if this redirection is used. - Configure the logout redirection path in module variables (default:
/).
Login
const login = async () => {
const success = await $auth.loginWithAccessKey(accessKey.value)
if (success) {
await navigateTo('/dashboard')
} else {
console.error('Login denied')
}
}Logout
await $auth.logout()Development
npm run dev:prepare
npm run devExperiment with the module in the playground environment 🎉
(Inspired by the Nuxt module guide)
Support
If you find this project helpful, please give it a star! ⭐
If you love it, consider forking it and taking it out for dinner. 🌟🍽️
