Nuxt/docs/2.guide/4.recipes/4.sessions-and-authentication.md

387 lines
14 KiB
Markdown
Raw Normal View History

2024-05-21 00:10:00 +00:00
---
title: 'Sessions and Authentication'
description: "User registration and authentication is an extremely common requirement in web apps. This recipe will show you how to implement basic user registration and authentication in you Nuxt app."
---
2024-06-10 21:24:49 +00:00
2024-05-21 00:10:00 +00:00
## Introduction
2024-06-10 21:24:49 +00:00
In this recipe we'll be setting up user registration, login, sessions, and authentication in a full-stack Nuxt app.
We'll be using [Nuxt Auth Utils](https://github.com/Atinux/nuxt-auth-utils) by [Altinux (Sébastien Chopin)](https://github.com/Atinux) which provides convenient utilities for managing front-end and back-end session data. We'll install and use this to get the core session management functionality we're going to need to manage user logins. For the database ORM we'll be using [Drizzle](https://orm.drizzle.team/) with [db0](https://db0.unjs.io/), but you can use any ORM or database connection strategy you prefer.
2024-05-21 00:10:00 +00:00
You'll need a `users` table in your database with the following columns:
- `id` (int, primary key, auto increment)
- `email` (varchar)
- `password` (varchar)
Additionally, we'll use [nuxt-aut-utils](https://github.com/Atinux/nuxt-auth-utils) by [Atinux](https://github.com/Atinux) to handle the authentication and session management.
## Steps
### 1. Install nuxt-auth-utils
2024-05-21 08:24:51 +00:00
2024-06-10 21:24:49 +00:00
Install the [auth-utils](https://github.com/Atinux/nuxt-auth-utils) module using the `nuxi` CLI.
2024-05-21 00:10:00 +00:00
```bash
npx nuxi@latest module add auth-utils
2024-05-21 00:10:00 +00:00
```
### 1a. (Optional) Add a session encryption key
Session cookies are encrypted. The encryption key is set from the `.env` file. This key will be added to your `.env` automatically when running in development mode the first time. However, you'll need to add this to your production environment before deploying.
```dotenv [.env]
NUXT_SESSION_PASSWORD=password-with-at-least-32-characters
```
### 2. Create a registration page
2024-05-21 08:24:51 +00:00
2024-06-10 21:24:49 +00:00
Create a new page in your Nuxt app for user registration. This page should have a form with fields for email and password. We'll intercept the form submission using `@submit.prevent` and use [`$fetch`](/docs/getting-started/data-fetching#fetch) to post the data to `/api/register`. Here's an example registration form for reference:
2024-05-21 00:10:00 +00:00
```vue [pages/register.vue]
<script setup lang="ts">
const form = ref({
name: "",
email: "",
password: "",
});
const error = ref(null);
async function submitForm() {
// clear any previous errors
error.value = null;
// perform the login
try {
await $fetch("/api/register", {
method: "POST",
body: form.value,
});
} catch (e) {
// if there's an error, set the error message and return early
error.value = "Error Registering User";
return;
}
// refresh the session status now that the user is logged in
const { fetch } = useUserSession();
await fetch();
// you may want to use something like Pinia to manage global state of the logged-in user
// update Pinia state here...
// take the user to the auth-only users index page now that they're logged in
await navigateTo("/users");
// Alternative - Don't use Nuxt Router here so that we can easily trigger a whole page load and get the whole UI refreshed now that the user is logged in.
// window.location.href = "/users";
2024-05-21 00:10:00 +00:00
}
</script>
<template>
<div>
<form class="space-y-2" @submit.prevent="submitForm">
<div>
<label for="name" class="block text-sm uppercase">Name</label>
<input id="name" name="name" v-model="form.name" class="rounded-md px-2 py-1" required />
</div>
<div>
<label for="email" class="block text-sm uppercase">Email</label>
<input id="email" name="email" v-model="form.email" class="rounded-md px-2 py-1" required />
</div>
<div>
<label for="password" class="block text-sm uppercase">password</label>
<input
id="password"
name="password"
v-model="form.password"
class="rounded-md px-2 py-1"
type="password"
required
/>
</div>
<div class="pt-2">
<button type="submit">Register</button>
</div>
<div v-if="error">{{ error }}</div>
</form>
</div>
</template>
```
### 3. Create an API route for registration
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
With the UI created we'll need to add a route to receive the registration form data. This route should accept a POST request with the email and password in the request body. It should hash the password and insert the user into the database. This route will only accept POST requests, so we'll follow the instructions for [API route methods](https://nuxt.com/docs/guide/directory-structure/server#matching-http-method) and name the file with `*.post.ts` to restrict the endpoint to only accept POST.
2024-06-10 21:24:49 +00:00
After we've successfully registered the user and stored the record in the database we can log them in by calling the `replaceUserSession` utility function from auth-utils. This utility function is automatically imported by the auth-utils module. We're using `replaceUserSession` here to make sure that any existing session data is cleared and replaced with the user login we're performing now.
2024-05-21 00:10:00 +00:00
2024-06-10 21:24:49 +00:00
The example file below is a very simple example of registration. You would probably want to add some error handling and nice response messages.
```typescript [/server/api/register.post.ts]
2024-05-21 00:10:00 +00:00
import users from "~/database/schema/users";
import getDatabase from "~/database/database";
import bcrypt from "bcrypt";
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const db = await getDatabase();
// has the password before creating the user record
const passwordHash = bcrypt.hashSync(body.password, 12);
await db.insert(users).values({
name: body.name,
email: body.email,
password: passwordHash,
});
2024-06-10 21:24:49 +00:00
// get the user record we just created
const user = (await db.select().from(users).where(eq(users.email, body.email)).limit(1))[0];
2024-06-10 21:24:49 +00:00
// log the user in as the user that was just created
await replaceUserSession(event, {
user: {
id: user.id,
name: user.name,
},
loggedInAt: new Date(),
});
await auth.login(event, user);
2024-05-21 00:10:00 +00:00
});
```
### 4. Create a login page
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
Create a new page in your Nuxt app for user login. This page should have a form with fields for email and password and should submit a POST request to `/api/login`.
Like the registration page, we'll intercept the form submission using `@submit.prevent` and use [`$fetch`](https://nuxt.com/docs/getting-started/data-fetching#fetch) to post the data to `/api/login`.
This is a very simple login form example, so you'd definitely want to add more validation and error checking in a real-world application.
```vue [pages/login.vue]
<script setup lang="ts">
import { ref } from "vue";
const form = ref({
email: "",
password: "",
});
const error = ref(null);
async function submitForm() {
// clear any previous errors
error.value = null;
// perform the login
try {
await $fetch("/api/auth/login", {
method: "POST",
body: loginForm.value,
});
} catch (e) {
// if there's an error, set the error message and return early
error.value = "Error logging in";
return;
}
// refresh the session status now that the user is logged in
const { fetch } = useUserSession();
await fetch();
// you may want to use something like Pinia to manage global state of the logged-in user
// update Pinia state here...
// take the user to the auth-only users index page now that they're logged in
await navigateTo("/users");
// Alternative - Don't use Nuxt Router here so that we can easily trigger a whole page load and get the whole UI refreshed now that the user is logged in.
// window.location.href = "/users";
2024-05-21 00:10:00 +00:00
}
</script>
<template>
<div>
<form class="space-y-2" @submit.prevent="submitForm">
<div>
<label for="email" class="block text-sm uppercase">Email</label>
<input id="email" name="email" v-model="form.email" class="rounded-md px-2 py-1" required />
</div>
<div>
<label for="password" class="block text-sm uppercase">password</label>
<input
id="password"
name="password"
v-model="form.password"
class="rounded-md px-2 py-1"
type="password"
required
/>
</div>
<div class="pt-2">
<button type="submit">Login</button>
</div>
<div v-if="error">{{ error }}</div>
</form>
</div>
</template>
```
### 5. Create an API route for login
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
With the login form created, we need to create an API route to handle the login request. This route should accept a POST request with the email and password in the request body and check the email and password against the database. If the user and password match, we'll set a session cookie to log the user in.
```typescript [server/api/auth/login.post.ts]
import users from "~/database/schema/users";
import getDatabase from "~/database/database";
import { eq } from "drizzle-orm";
import bcrypt from "bcrypt";
const db = await getDatabase();
const user = (await db.select().from(users).where(eq(users.email, body.email)).limit(1))?.[0];
// compare the password hash
if (!user || !bcrypt.compareSync(body.password, user.password)) {
// throw an error if the user is not found or the password doesn't match
throw createError({
statusCode: 401,
statusMessage: "Invalid email or password",
});
}
// set the session
await replaceUserSession(event, {
2024-05-21 00:10:00 +00:00
user: {
id: user.id,
name: user.name,
},
loggedInAt: new Date(),
});
```
The user should now be logged in! With the session set, we can get the current user session in any API route or page by calling `getUserSession(event)` which is auto-imported as a util function from the `nuxt-auth-utils` package.
### 6. Create a logout API route
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
Users need to be able to log out, so we should create an API route to allow them to do this. This should require post request as well, just like login. We'll clear the session when this endpoint is called.
```typescript [server/api/auth/logout.post.ts]
export default defineEventHandler(async (event) => {
// Clear the current user session
await clearUserSession(event);
});
```
### 7. Create a server utility function to protect routes
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
Protecting server routes is key to making sure your data are safe. Front-end middleware is helpful for the user, but without back-end protection your data can still be accessed. Because of this, it is critical that we create a server utility function to protect any API routes with sensitive data. For these sensitive routes, we should return a 401 error if the user is not logged in.
We'll create a utility function which will make a reusable function to help protect our endpoints. Functions in the `/server/util` folder are auto-imported to server endpoints. You can read about the `/server/util` folder [here](https://nuxt.com/docs/guide/directory-structure/utils). This utility function will help us prevent data from being accessed by users who are not logged in.
The file will be named `requireUserLoggedIn.ts` which will make this utl function available in any server route by calling `requireUserLoggedIn(event)`.
```typescript [server/utils/requireUserLoggedIn.ts]
export default async (event) => {
await requireUserSession(event);
};
```
### 8. Protect a route with the utility function
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
Now that we have the utility function to protect routes, we can use it in any API route to ensure that only logged-in users can access the route.
In the example below, we use the `requireUserLoggedIn` utility function to protect the `/api/users.get` route. This route will only be accessible to logged-in users.
```typescript [server/api/users.get.ts]
import getDatabase from "~/database/database";
import users from "~/database/schema/users";
import requireUserLoggedIn from "~/server/utils/requireUserLoggedIn";
export default defineEventHandler(async (event) => {
// make sure the user is logged in
await requireUserLoggedIn(event);
const db = await getDatabase();
// Send back the list of users
const userList = await db.select({ name: users.name, id: users.id }).from(users).limit(10);
return userList;
});
```
### 9. Create a front-end middleware to protect routes
2024-05-21 08:24:51 +00:00
Our data are safe with the back-end route in place, but without doing anything else, unauthenticated users would probably get some odd data when trying to access the `/users` page. We should create a [front-end middleware](https://nuxt.com/docs/guide/directory-structure/middleware) to protect the route on the client side and redirect users to a login page.
2024-05-21 00:10:00 +00:00
`nuxt-auth-utils` provides a convenient `useUserSession` composable which we'll use to check if the user is actually logged in, and redirect them if they are not.
```typescript [middleware/RedirectIfNotAuthenticated.ts]
export default defineNuxtRouteMiddleware(() => {
// check if the user is logged in
const { loggedIn } = useUserSession();
// redirect the user to the login screen if they're not authenticated
if (!loggedIn.value) {
return navigateTo("/login");
}
return null;
});
```
### 10. Protect a route with the front-end middleware
2024-05-21 08:24:51 +00:00
2024-05-21 00:10:00 +00:00
Now that we have the front-end middleware to protect front-end routes, we can use it in any page to ensure that only logged-in users can access the route. Users will be redirected to the login page if they are not authenticated.
We'll use [`definePageMeta`](https://nuxt.com/docs/api/utils/define-page-meta) to apply the middleware to the route that we want to protect.
2024-05-21 00:16:04 +00:00
::important
:warning: Remember that your data aren't really secure without back-end protection! Always secure your data on the back-end first before worrying about the front-end.
::
2024-05-21 00:10:00 +00:00
```vue [pages/users/index.vue]
<script setup lang="ts">
const { data: users } = await useFetch("/api/users");
definePageMeta({
middleware: ["redirect-if-not-authenticated"],
});
</script>
<template>
<div>
<div class="pb-4 text-sm font-semibold uppercase">Users List</div>
<div>
<ul class="space-y-4">
<li v-for="user in users" :key="user.id">
<NuxtLink :to="`/users/${user.id}`">
<div class="px-4 py-2 hover:bg-gray-600">{{ user.name }}</div>
</NuxtLink>
</li>
</ul>
</div>
</div>
</template>
```
2024-05-21 08:24:51 +00:00
### Complete
2024-05-21 00:10:00 +00:00
We've successfully set up user registration and authentication in our Nuxt app. Users can now register, log in, and log out. We've also protected sensitive routes on the server and client side to ensure that only authenticated users can access them.