
Security News
npm ‘is’ Package Hijacked in Expanding Supply Chain Attack
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.
nuxt-jwt-auth
Advanced tools
A Nuxt module to authenticate on a custom backend (Laravel Sanctum) via jwt token
A Nuxt module to authenticate on a custom backend (Laravel) via jwt token.
$jwtAuth
pluginuseJwtAuth
composablenuxt-jwt-auth
dependency to your project# Using pnpm
pnpm add -D nuxt-jwt-auth
# Using yarn
yarn add --dev nuxt-jwt-auth
# Using npm
npm install --save-dev nuxt-jwt-auth
nuxt-jwt-auth
to the modules
section of nuxt.config.ts
// nuxt.config.ts
export default defineNuxtConfig({
modules: [
'nuxt-jwt-auth'
]
})
nuxt-jwt-auth
// nuxt.config.ts
export default defineNuxtConfig({
// ...
nuxtJwtAuth: {
baseUrl: 'http://homestead.test/api', // URL of your backend
endpoints: {
login: '/login', // Where to request login (POST)
logout: '/logout', // Where to request logout (POST)
user: '/user', // Where to request user data (GET)
signup: '/signup' // Where to request signup (POST)
},
redirects: {
home: '/', // Where to redirect after successfull login and logout
login: '/login', // Where to redirect if user is not logged in and accesses a logged-only route
logout: '/logout' // Where to redirect if user is logged in and accesses a guest-only route
}
}
})
This modules provides the $jwtAuth plugin, which contains login and logout methods.
Login function accepts credentials, which are passed as-is to the backend, as first argument. You can optionally provide a callback function as second argument. This function will receive the response from the backend.
If no callback function is provided, the user will be redirected to the home
route specified in configuration after successful login.
<script setup>
const { $jwtAuth } = useNuxtApp()
const router = useRouter()
async function login() {
try {
await $jwtAuth.login(
{
email: 'email@example.com',
password: 'supersecretpassword'
},
// optional callback function
(data) => {
console.log(data)
window.location.replace('/')
}
)
} catch (e) {
// your error handling
}
}
</script>
⚠️ If using custom callback function, you must always navigate to another route using window.location.replace()
. Some auth data may not be updated if navigating "in-app" with router.push()
or nuxt's navigateTo()
⚠️ It is requested that the backend responds to the login request with a JSON object containing both token and user properties:
{
"token": "1|TjVJavoOkerwXViiRwLBLsd1xGSRoYosiO87zSEr",
"user": {
"name": "Mario",
"surname": "Rossi",
"address": "Fake St. 123"
}
}
This modules provides the $jwtAuth plugin, which contains signup method.
Signup function accepts registration data, which are passed as-is to the backend, as first argument. You can optionally provide a callback function as second argument. This function will receive the response from the backend.
If no callback function is provided, the user will be redirected to the home
route specified in configuration after successful signup.
<script setup>
const { $jwtAuth } = useNuxtApp()
const router = useRouter()
async function signup() {
try {
await $jwtAuth.signup(
{
username: 'Mario Rossi',
email: 'email@example.com',
password: 'supersecretpassword',
password_confirm: 'supersecretpassword'
},
// optional callback function
(data) => {
console.log(data)
router.push('/account')
}
)
} catch (e) {
// your error handling
}
}
</script>
Please note that it is requested that the backend responds to the signup request with a JSON object containing both token and user properties:
{
"token": "1|TjVJavoOkerwXViiRwLBLsd1xGSRoYosiO87zSEr",
"user": {
"name": "Mario",
"surname": "Rossi",
"address": "Fake St. 123"
}
}
This modules provides two route middleware you can optionally add to pages.
Use this middleware in pages where user must be logged in (such as /account
)
<script setup>
definePageMeta({
middleware: 'auth'
})
</script>
Use this middleware in pages where user must not be logged in (such as /login
)
<script setup>
definePageMeta({
middleware: 'guest'
})
</script>
This modules provides the useJwtAuth composable, which you can use to obtain useful auth-related data, such as user
, token
, loggedIn
state.
⚠️ All variables obtained from useJwtAuth are computed properties, to reflect changes in cookie data.
<template>
<h1>Hello,</h1>
<h2 v-if="loggedIn">{{user.name}}</h2>
</template>
<script setup>
const { user, loggedIn } = useJwtAuth()
</script>
ℹ️ If using typescript, you can specify the user type!
<script setup lang="ts">
interface User {
name: string
}
const { user, loggedIn } = useJwtAuth<User>()
console.log('user name is', user.name) // user.name is of type string now
</script>
By using the fetch function of $jwtAuth plugin, you can send standard api requests to the backend.
<script setup>
const { $jwtAuth } = useNuxtApp()
async function fetchMyData() {
try {
const myData = await $jwtAuth.fetch('my-api-route')
// do something with received data...
} catch (e) {
// your error handling
}
}
</script>
This modules provides the $jwtAuth plugin, which contains login and logout methods.
<script setup>
const { $jwtAuth } = useNuxtApp()
async function logout() {
try {
await $jwtAuth.logout()
} catch (e) {
// your error handling
}
}
</script>
In special cases, you can manage authentication externally and set token and user data
by using setUser
, setToken
or setTokenAndUser
functions.
<script setup>
const { $jwtAuth } = useNuxtApp()
async function externalLogin() {
try {
// special login executed externally
const token = "1|TjVJavoOkerwXViiRwLBLsd1xGSRoYosiO87zSEr"
const user = {
"name": "Mario",
"surname": "Rossi",
"address": "Fake St. 123"
}
$jwtAuth.setToken(token)
$jwtAuth.setUser(user)
// same as
$jwtAuth.setTokenAndUser({
token,
user
})
} catch (e) {
// your error handling
}
}
</script>
User data displayed in the nuxt layout (ex. username on the right of an app bar) is not updated until a full server page reload. So, if you provide a callback to the login method and in this callback you push to another route (on the client), user data will not be displayed in the layout.
This is a bug/feature of nuxt itself, which does not refresh layouts data when navigating on the client.
To solve this, add key argument to nuxt-layout:
<nuxt-layout :key="$route.path">
<nuxt-page />
</nuxt-layout>
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Build the playground
npm run dev:build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Release new version
npm run release
v1.0.0
FAQs
A Nuxt module to authenticate on a custom backend (Laravel Sanctum) via jwt token
We found that nuxt-jwt-auth demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.
Security News
A critical flaw in the popular npm form-data package could allow HTTP parameter pollution, affecting millions of projects until patched versions are adopted.
Security News
Bun 1.2.19 introduces isolated installs for smoother monorepo workflows, along with performance boosts, new tooling, and key compatibility fixes.