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": "[email protected]",
"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": "[email protected]",
"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"
}
}
}
}
5 Replies
kapa.ai
kapa.ai2mo 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.ai2mo ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Adnan Erlansyah
Adnan ErlansyahOP2mo 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
Cue2mo ago
You need to @ mention the bot
Adnan Erlansyah
Adnan ErlansyahOP2mo ago
Oh oke sir, thank you.
Want results from more Discord servers?
Add your server