How to make middleware auth in nuxtjs3?

Hello everyone, can anyone help me again about how we can make the middleware for authentication user & role user in nuxtjs 3. My Response Data looking like this:
{
"status": true,
"message": "Login successful",
"data": {
"user": {
"id": 7,
"rememberToken": null,
"fullName": "User Example",
"email": "user@example.com",
"phone": null,
"province": null,
"city": null,
"address": null,
"gender": "l",
"roleId": 1,
"experience": null,
"rating": 0,
"photo": null,
"biography": null,
"status": 1,
"isVerified": 1,
"createdAt": "2024-10-30T07:43:48.000+00:00",
"updatedAt": "2024-10-30T07:43:48.000+00:00"
},
"token": {
"headers": {
"authorization": "Bearer oat_Mjk.aWo0Z3lxSEFXS0NUaGt5ejFhbVNwU2xhT3pMM3dRYUlXT29mMVFCRzEyMTcxMzI4MzM"
}
}
}
}
{
"status": true,
"message": "Login successful",
"data": {
"user": {
"id": 7,
"rememberToken": null,
"fullName": "User Example",
"email": "user@example.com",
"phone": null,
"province": null,
"city": null,
"address": null,
"gender": "l",
"roleId": 1,
"experience": null,
"rating": 0,
"photo": null,
"biography": null,
"status": 1,
"isVerified": 1,
"createdAt": "2024-10-30T07:43:48.000+00:00",
"updatedAt": "2024-10-30T07:43:48.000+00:00"
},
"token": {
"headers": {
"authorization": "Bearer oat_Mjk.aWo0Z3lxSEFXS0NUaGt5ejFhbVNwU2xhT3pMM3dRYUlXT29mMVFCRzEyMTcxMzI4MzM"
}
}
}
}
13 Replies
kapa.ai
kapa.ai11mo ago
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To create an authentication middleware in Nuxt 3, you can follow these steps: 1. Create a new file named auth.ts in the middleware directory of your Nuxt 3 project. 2. Use the defineNuxtRouteMiddleware function to define your middleware. Here's an example of how you can implement the authentication middleware:
export default defineNuxtRouteMiddleware((to, from) => {
const userStore = useState('user');
const token = useState('token');

// Check if the user is authenticated
if (!userStore.value || !token.value) {
// If not authenticated, redirect to login page
return navigateTo('/login');
}

// Check user role if needed
if (to.meta.requiresAdmin && userStore.value.roleId !== 1) {
// If the route requires admin role and user is not admin, redirect to home
return navigateTo('/');
}
});
export default defineNuxtRouteMiddleware((to, from) => {
const userStore = useState('user');
const token = useState('token');

// Check if the user is authenticated
if (!userStore.value || !token.value) {
// If not authenticated, redirect to login page
return navigateTo('/login');
}

// Check user role if needed
if (to.meta.requiresAdmin && userStore.value.roleId !== 1) {
// If the route requires admin role and user is not admin, redirect to home
return navigateTo('/');
}
});
This middleware checks if the user is authenticated by verifying the presence of user data and token in the state. If not authenticated, it redirects to the login page. It also includes an example of role-based access control. 3. To use this middleware, you can add it to your pages using the definePageMeta function:
<script setup>
definePageMeta({
middleware: ["auth"]
});
</script>
<script setup>
definePageMeta({
middleware: ["auth"]
});
</script>
4. To store the user data and token after a successful login, you can use the useState composable in your login component or page:
<script setup>
const { data: loginResponse } = await useFetch('/api/login', {
method: 'POST',
body: { /* your login credentials */ }
});
if (loginResponse.value.status) {
const user = useState('user', () => loginResponse.value.data.user);
const token = useState('token', () => loginResponse.value.data.token.headers.authorization);

// Set the user and token state
user.value = loginResponse.value.data.user;
token.value = loginResponse.value.data.token.headers.authorization;

// Redirect to dashboard or home page
navigateTo('/dashboard');
}
</script>
<script setup>
const { data: loginResponse } = await useFetch('/api/login', {
method: 'POST',
body: { /* your login credentials */ }
});
if (loginResponse.value.status) {
const user = useState('user', () => loginResponse.value.data.user);
const token = useState('token', () => loginResponse.value.data.token.headers.authorization);

// Set the user and token state
user.value = loginResponse.value.data.user;
token.value = loginResponse.value.data.token.headers.authorization;

// Redirect to dashboard or home page
navigateTo('/dashboard');
}
</script>
This approach uses Nuxt 3's built-in state management with useState and the useFetch composable for API calls. The middleware can then access this state to check for authentication. Remember to handle token expiration and refreshing as needed in your application. For more detailed information on Nuxt 3 middleware, you can refer to the Nuxt 3 Middleware Documentation (https://nuxt.com/docs/guide/directory-structure/middleware). Stack Overflow - Nuxt 3 Middleware Example (https://stackoverflow.com/questions/77246657) Nuxt 3 Route Middleware Documentation (https://nuxt.com/docs/guide/directory-structure/middleware#middleware) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai11mo ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Adnan Erlansyah
Adnan ErlansyahOP11mo ago
How about to save the state of user and token in the browser to tracking it whether the user is still valid or not. How about to save the state of user and token in the browser to tracking it whether the user is still valid or not.
Cue
Cue11mo ago
You need to @ mention the bot
Adnan Erlansyah
Adnan ErlansyahOP11mo ago
Oh oke sir, thank you.
rwcrabtree
rwcrabtree5mo ago
@kapa.ai how do you protect api routes not associated with a specific page?
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- To protect API routes in Nuxt 3 that are not associated with a specific page, you should implement authentication checks directly within your server API route handlers. This ensures that only authenticated users can access sensitive endpoints, regardless of how the API is called. A common approach is to use a utility function (such as requireUserSession) at the top of your API handler. If the user is not authenticated, this function should throw a 401 error, preventing access to the route. Here’s an example from the official Nuxt documentation:
// server/api/user/stats.get.ts

export default defineEventHandler(async (event) => {
// Ensure the user is logged in
// This will throw a 401 error if the request doesn't come from a valid user session
const { user } = await requireUserSession(event)

// Fetch and return data for the authenticated user
return {}
})
// server/api/user/stats.get.ts

export default defineEventHandler(async (event) => {
// Ensure the user is logged in
// This will throw a 401 error if the request doesn't come from a valid user session
const { user } = await requireUserSession(event)

// Fetch and return data for the authenticated user
return {}
})
This pattern ensures your API routes are protected on the server side, independent of any client-side middleware or page association. Always protect sensitive data on the server, as client-side checks alone are not sufficient for security Protect API Routes. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@391697235995525121> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
rwcrabtree
rwcrabtree5mo ago
@kapa.ai can you show me an example of what the requireUserSession helper function would look like in the context your middleware example?
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Certainly! In the context of Nuxt 3 and the nuxt-auth-utils module, the requireUserSession helper is provided by the module itself to protect your API routes. You do not need to implement it yourself if you use this module. Here’s how it is used in a server API route:
// server/api/user/stats.get.ts

export default defineEventHandler(async (event) => {
// This will throw a 401 error if the request doesn't come from a valid user session
const { user } = await requireUserSession(event)

// You can now safely use `user` knowing the request is authenticated
return {}
})
// server/api/user/stats.get.ts

export default defineEventHandler(async (event) => {
// This will throw a 401 error if the request doesn't come from a valid user session
const { user } = await requireUserSession(event)

// You can now safely use `user` knowing the request is authenticated
return {}
})
The requireUserSession function checks for a valid session (typically via a sealed cookie) and throws a 401 error if the user is not authenticated. This is the recommended way to protect server-side API routes in Nuxt 3 when using nuxt-auth-utils Protect API Routes. If you are not using nuxt-auth-utils, the knowledge sources do not provide an explicit implementation of requireUserSession. The documentation assumes you are using the module, which handles session validation and error throwing for you. If you need to implement your own, you would need to handle session or token validation manually, but there is no example of that in the provided sources. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@391697235995525121> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
rwcrabtree
rwcrabtree4mo ago
hi all, how do I uninstall/remove a nuxt module?
killjoy
killjoy4mo ago
You'd remove it from your modules array/folder.

Did you find this page helpful?