Skip to content

Nuxt 3 user authentication system using mongoDB to store users & sessions.

Notifications You must be signed in to change notification settings

timb-103/nuxt-mongodb-auth

Repository files navigation

Nuxt 3 MongoDB Auth

A simple Nuxt 3 user authentication system using mongoDB to store users & sessions.

Basic Example

Install

Install the module:

npm i -D nuxt-mongodb-auth

Add nuxt-mongodb-auth to the modules array in nuxt.config.ts:

export default defineNuxtConfig({
  modules: ['nuxt-mongodb-auth'],
})

Add your mongo connection string and main database name in your .env file:

MONGO_CONNECTION_STRING=
MONGO_DB=

Usage

To handle the user auth flow, you can use these simple composables in any of your pages:

  • useAuthRegister()
  • useAuthLogin()
  • useAuthLogout()
  • useAuthUser()

Server side authentication

When calling your protected API routes, add this at the top of your file:

import { requiresAuthSession } from '#nuxt-mongodb-auth'

export default defineEventHandler(async (event) => {
  const user = await requiresAuthSession(event)
})

If the user has no authorized session, it will throw an error and return before executing any more code.

MongoDB Connection

You can also access the same mongo connection from your server routes:

import { mongo } from '#nuxt-mongodb-auth'

const db = mongo.db()
const response = await db.collection('YOUR_COLLECTION').find()

About

Nuxt 3 user authentication system using mongoDB to store users & sessions.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published