Skip to content

rrd108/nuxt-token-authentication

Repository files navigation

Nuxt Token Authentication

npm version npm downloads License Nuxt

This Nuxt module simplifies user authentication using HTTP headers, streamlining the integration of token-based authorization into your application.

Features

  • Flexible Authentication: Supports various database backends (MySQL, SQLite, MongoDB, Microsoft SQL Server, PlanetScale, CockroachDB, Supabase, Neon, Turso) for user and token management.
  • Customizable Token Handling: You can configure the token header and the routes that do not require authentication.
  • Streamlined Integration: Easy setup with minimal configuration.
  • Seamless error handling for authentication failures.
  • Production-Ready: Secure practices for handling sensitive token data.

Quick Setup

1. Add nuxt-token-authentication dependency to your project

# Using pnpm
pnpm add nuxt-token-authentication

# Using yarn
yarn add nuxt-token-authentication

# Using npm
npm install nuxt-token-authentication

2. Add nuxt-token-authentication to the modules section of nuxt.config.ts

export default defineNuxtConfig({
  modules: ["nuxt-token-authentication"],
  nuxtTokenAuthentication: {
    //authTable: "users", // users table name, default: "users"
    //tokenField: "token",  // name of the field in your table that stores the token, default: "token"
    //tokenHeader: "Token", // name of the authentication header, you can use or "Authorization", or anything else you want, default: "Token"
    // prefix: "Bearer" // value used to prefix the token's value, default is empty
    noAuthRoutes: ["POST:/api/auth/getToken"], // list of routes that do not require authentication
  },
});

3. Set Prisma schema

The module will install Prisma for you. You can use the following steps to set up Prisma. We assume you have an existing database, with at least one table to store the users, and the table has a column for the token, named token.

3.1. npx prisma init to create a new Prisma schema file. It will create a new directory called prisma with a schema.prisma file inside it.

3.2. In your /.env file, set the DATABASE_URL environment variable to point to your existing database. If your database has no tables yet, read Getting Started with Prisma.

Supported databases: PostgreSQL, MySQL, SQLite, MongoDB, Microsoft SQL Server, PlanetScale, CockroachDB, Supabase, Neon, Turso

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

3.3. Set the provider of the datasource block in schema.prisma to match your database.

3.4. Run npx prisma db pull to turn your database schema into a Prisma schema.

3.5. Run npx prisma generate to generate the Prisma Client. You can then start querying your database.

That's it! You can now use Nuxt Token Authentication in your Nuxt app ✨

Creating the API endpoints

Let's suppose you want to authenticate the users at the url api/auth/getToken with a POST request. You can use the following code to create the API endpoint.

Create a file at /server/api/auth/getToken.post.ts with the following code. Feel free to modify if your users table does not identify the users by their email and password but other fields. Do not forget to change data.password (coming from the user's request) to a hashed password.

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

export default defineEventHandler(async (event) => {
  const data = await readBody(event);

  const options = useRuntimeConfig().public.nuxtTokenAuthentication;
  const user = await prisma[options.authTable].findUnique({
    where: {
      email: data.email,
      password: data.password,
    },
  });

  delete user?.password;
  return { user };
});

Now you can send a POST request to /api/auth/getToken with 2 fields in the body: email and password. If the user exists, the server will return the user's data, including the token. Any other routes (except the ones you set in noAuthRoutes) will require the token to be sent in the header.

Development

# Install dependencies
yarn

# Generate type stubs
yarn dev:prepare

# Develop with the playground
yarn dev

# Build the playground
yarn dev:build

# Run ESLint
yarn lint

# Set up for testing
npx prisma db push
npx prisma db seed
# and create .env files for the test folders with DATABASE_URL="file:/fullPath/prisma/dev.db"


# Run Vitest
yarn test
yarn test:watch

# Release new version
yarn release