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."
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.
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.
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.
The first page we'll need is a page for users to register and create new accounts. Create a new Vue page in your Nuxt app at `/pages/register.vue` 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 the [`$fetch`](/docs/getting-started/data-fetching#fetch) utility to post the data to `/api/register`. This form POST will be received by Nuxt in an API route which we will set up next.
// 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.
With the user interface 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.
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.
When registered users return to your site they'll need to be able to log back in. Create a new page at `/pages/login.vue` 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.
// 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. This will perform a full-page load.
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.
This server API route should be at `/server/api/auth/login.post.ts`. Just like the registration form endpoint, suffixing the filename in `.post.ts.` means that this handler will only respond to post requests.
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.
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.
We'll use the `clearUserSession` from the `auth-utils` module to log the user out and clear the session data. This function is automatically imported from the module by Nuxt, so we don't need to manually import it.
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 protect any API routes with sensitive data. For these sensitive routes, we should return a 401 error if the user is not logged in.
The `auth-utils` module provides the `requireUserSession` utility function to help make sure that users are logged in and have an active session. We can use this to protect our different endpoints. Like many of the other utilities from the auth module, it is automatically imported in our server endpoints.
In the example below, we use the `requireUserSession` utility function to protect the `/server/api/users.get.ts` server route. This route will only be accessible to logged-in users.
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.
`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.
We'll create a middleware in the `/middleware` directory. Unlike on the server, front-end middleware is not automatically applied to all endpoints, and we'll need to specify where we want it applied.
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.
: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.
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.