Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
</p>
<!-- Badges End -->

> Authentication built for Nuxt 3+! Easily add authentication via OAuth providers, credentials or Email Magic URLs!
> Authentication built for Nuxt 4! Easily add authentication via OAuth providers, credentials or Email Magic URLs!

## Quick Start

Expand Down Expand Up @@ -62,8 +62,8 @@ Then visit the [Quick Start documentation](https://auth.sidebase.io/guide/gettin

## Features

`@sidebase/nuxt-auth` is a library with the goal of supporting authentication for any universal Nuxt 3+ application. At the moment two providers are supported:
- [`authjs`](https://auth.sidebase.io/guide/authjs/quick-start): for non-static apps that want to use [Auth.js / NextAuth.js](https://github.com/nextauthjs/next-auth) to offer the reliability & convenience of a 23k star library to the Nuxt 3+ ecosystem with a native developer experience (DX)
`@sidebase/nuxt-auth` is a library with the goal of supporting authentication for any universal Nuxt 4 application. At the moment three providers are supported:
- [`authjs`](https://auth.sidebase.io/guide/authjs/quick-start): for non-static apps that want to use [Auth.js / NextAuth.js](https://github.com/nextauthjs/next-auth) to offer the reliability & convenience of a 23k star library to the Nuxt 4 ecosystem with a native developer experience (DX)
- [`local`](https://auth.sidebase.io/guide/local/quick-start): for static pages that rely on an external backend with a credential flow for authentication. The Local Provider also supports refresh tokens since `v0.9.0`. Read more [here](https://auth.sidebase.io/upgrade/version-0.9.0).

You can find a full list of our features, as well as which provider supports each feature [on our docs](https://auth.sidebase.io/guide/getting-started/choose-provider).
Expand Down Expand Up @@ -142,9 +142,9 @@ We have one playground per provider:
- [`authjs`](./playground-authjs)
- [`local`](./playground-local)

##### How to test static Nuxt 3+ apps?
##### How to test static Nuxt 4 apps?

To test static Nuxt 3+ apps we want to run a static frontend and a separate backend that will take over authentication:
To test static Nuxt 4 apps we want to run a static frontend and a separate backend that will take over authentication:
1. `playground-local/nuxt.config.ts`: Add `baseURL: 'http://localhost:3001'` to the `auth`-config
2. Start the static frontend:
```sh
Expand All @@ -154,7 +154,7 @@ To test static Nuxt 3+ apps we want to run a static frontend and a separate back

pnpm start
```
3. Start the authentication backend (we use a second instance of the same nuxt3 app):
3. Start the authentication backend (we use a second instance of the same Nuxt 4 app):
```sh
cd playground-local

Expand All @@ -171,7 +171,7 @@ Thank you to everyone who has contributed to this project by writing issues or o

## Acknowledgments

`@sidebase/nuxt-auth` is supported by all of our amazing contributors and the [Nuxt 3+ team](https://nuxters.nuxt.com/)!
`@sidebase/nuxt-auth` is supported by all of our amazing contributors and the [Nuxt 4 team](https://nuxters.nuxt.com/)!

<a href="https://github.com/sidebase/nuxt-auth/graphs/contributors">
<img src="https://contrib.rocks/image?repo=sidebase/nuxt-auth" />
Expand Down
4 changes: 4 additions & 0 deletions devbox.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "https://raw.githubusercontent.com/jetpack-io/devbox/0.10.3/.schema/devbox.schema.json",
"packages": ["nodejs@22"]
}
2 changes: 1 addition & 1 deletion docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { headConfig, sitemapConfig } from './head'
export default defineConfig({
title: 'NuxtAuth',
titleTemplate: ':title - by sidebase',
description: 'Authentication for Nuxt',
description: 'Authentication for Nuxt 4',
base: '/',
cleanUrls: true,
lang: 'en-US',
Expand Down
2 changes: 1 addition & 1 deletion docs/.vitepress/head.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const sitemapConfig = {
export const headConfig: HeadConfig[] = [
['link', { rel: 'icon', href: '/favicon.ico' }],
['meta', { name: 'theme-color', content: '#30A36C' }],
['meta', { property: 'og:title', content: 'NuxtAuth | Authentication for Nuxt' }],
['meta', { property: 'og:title', content: 'NuxtAuth | Authentication for Nuxt 4' }],
['meta', { property: 'og:description', content: 'User authentication and sessions via authjs' }],
['meta', { property: 'og:site_name', content: 'NuxtAuth' }],
['meta', { property: 'og:type', content: 'website' }],
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/advanced/deployment/self-hosted.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Self Hosting

This guide will explain how you can self-host a Nuxt3 application running NuxtAuth.
This guide will explain how you can self-host a Nuxt 4 application running NuxtAuth.

## Authjs Provider

Expand Down
93 changes: 20 additions & 73 deletions docs/guide/application-side/protecting-pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,90 +23,40 @@ export default defineNuxtConfig({
})
```

If you'd like to further customize the global middleware, you can pass an object of configurations to `globalAppMiddleware`. See the API reference [here](./configuration#globalappmiddleware).
If you like to further customize the global middleware, you can pass an object of configurations to `globalAppMiddleware`. See the API reference here.

When you use the global middleware, but want to disable it on some pages, use the [`definePageMeta`](https://nuxt.com/docs/api/utils/define-page-meta) macro to set the authentication metadata for a single page.
### Disabling the Global Middleware

If the global middleware is disabled, you can manually add the middleware to individual pages. This is only available if the global middleware is disabled, as you will get an error along the lines of `Error: Unknown route middleware: 'auth'`. This is because the auth middleware is then added globally and not available to use as a local, page-specific middleware.

```vue
<script setup lang="ts">
<script lang="ts" setup>
definePageMeta({
auth: false // This would disable the middleware for the page
middleware: 'sidebase-auth'
})
</script>

<template>
I am not protected anymore!
Only I am protected!
</template>
```

## Local Middleware

When you are not using the global middleware, you can still protect your pages individually using local middleware. To enable or disable the middleware on a single page, use the `auth` property on `definePageMeta`.
To locally enable or disable the middleware on a single page, you can use the [`definePageMeta`](https://nuxt.com/docs/api/utils/define-page-meta) macro to set the authentication metadata for a single page.

By setting `auth` to `true`, you can automatically enable the middleware on the page:

```vue [Add middleware automatically]
<script lang="ts" setup>
```vue
<script setup lang="ts">
definePageMeta({
auth: true // [!code focus]
auth: false
})
</script>

<template>
I am now protected again!
I am not protected anymore!
</template>
```

:::info

When you use the automatic adding, the middleware will always be added after the other middleware you defined. This means that the following

```ts
definePageMeta({
auth: true,
middleware: 'other-middleware'
})
```

will be interpreted as:

```ts
definePageMeta({
auth: true,
middleware: ['other-middleware', 'sidebase-auth']
})
```

:::

### Manually adding local middleware

Another way of enabling the middleware is by manually specifying it:

```vue [Add middleware manually]
<script lang="ts" setup>
definePageMeta({
middleware: 'sidebase-auth' // [!code focus]
})
</script>
```

This gives you a total control of the order in which the different middlewares are executed:

```vue
<script lang="ts" setup>
definePageMeta({
middleware: ['first-middleware', 'sidebase-auth', 'last-middleware'] // [!code focus]
})
</script>
```

:::warning

Using local middleware is only available if the global middleware was disabled, as otherwise you will get an error along the lines of `Error: Unknown route middleware: 'auth'`. This is because the auth middleware is then added globally and not available to use as a local, page-specific middleware.

:::

### Middleware options

`auth` can be either a boolean or an object of further middleware configurations.
Expand All @@ -132,7 +82,7 @@ Whether to allow only unauthenticated users to access this page. Authenticated u

If you want to let everyone see the page, set `auth: false` instead (see [Local Middleware](#local-middleware)).

:::danger
:::warning
This option is required from `0.9.4` onwards to prevent ambiguity ([related issue](https://github.com/sidebase/nuxt-auth/issues/926)). Make sure you set it, otherwise [Guest Mode](#guest-mode) will be **enabled** by default β€” your guests would be able to see the page, but your authenticated users would be redirected away.
:::

Expand Down Expand Up @@ -172,9 +122,13 @@ definePageMeta({

You may create your own application-side middleware in order to implement custom, more advanced authentication logic.

:::warning
Creating a custom middleware is an advanced, experimental option and may result in unexpected or undesired behavior if you are not familiar with advanced Nuxt 4 concepts.
:::

To implement your custom middleware:
- Create an application-side middleware that applies either globally or is named (see the [Nuxt docs](https://nuxt.com/docs/4.x/api/utils/define-page-meta#defining-middleware) for more);
- Add logic based on [`useAuth`](/guide/application-side/session-access) to it.
- Create an application-side middleware that applies either globally or is named (see the Nuxt docs for more)
- Add logic based on [`useAuth`](/guide/application-side/session-access) to it

When adding the logic, you need to watch out when calling other `async` composable functions. This can lead to `context`-problems in Nuxt, see [the explanation for this here](https://github.com/nuxt/framework/issues/5740#issuecomment-1229197529). In order to avoid these problems, you will need to either:

Expand All @@ -197,15 +151,8 @@ export default defineNuxtRouteMiddleware((to) => {
* We cannot directly call and/or return `signIn` here as `signIn` uses async composables under the hood, leading to "nuxt instance undefined errors", see https://github.com/nuxt/framework/issues/5740#issuecomment-1229197529
*
* So to avoid calling it, we return it immediately.
*
* Important: you need to explicitly handle the value returned by the `signIn`,
* for example by changing it to `false` (to abort further navigation) or `undefined` (to process other middleware).
* See https://github.com/sidebase/nuxt-auth/issues/1042
*/
return signIn(
undefined,
{ callbackUrl: to.path }
).then(() => /* abort further route navigation */ false)
return signIn(undefined, { callbackUrl: to.path }) as ReturnType<typeof navigateTo>
})
```

Expand Down
2 changes: 1 addition & 1 deletion docs/guide/authjs/server-side/session-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default eventHandler(async (event) => {
This is inspired by [the `getServerSession`](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes) of NextAuth.js. It also avoids an external HTTP `GET` request to the `/api/auth/sessions` endpoint, instead directly calling a pure JS-method.

:::warning Note:
If you use [Nuxt's `useFetch`](https://nuxt.com/docs/api/composables/use-fetch) from your app-components to fetch data from an endpoint that uses `getServerSession` or `getToken` you will need to manually pass along cookies as [Nuxt universal rendering](https://nuxt.com/docs/guide/concepts/rendering#universal-rendering) will not do this per-default when it runs on the server-side. Not passing along cookies will result in `getServerSession` returning `null` when it is called from the server-side as no auth cookies will exist. Here's an example that manually passes along cookies:
If you use [Nuxt's `useFetch`](https://nuxt.com/docs/api/composables/use-fetch) from your app-components to fetch data from an endpoint that uses `getServerSession` or `getToken` you will need to manually pass along cookies as [Nuxt 4 universal rendering](https://nuxt.com/docs/guide/concepts/rendering#universal-rendering) will not do this per-default when it runs on the server-side. Not passing along cookies will result in `getServerSession` returning `null` when it is called from the server-side as no auth cookies will exist. Here's an example that manually passes along cookies:
```ts
const headers = useRequestHeaders(['cookie']) as HeadersInit
const { data: token } = await useFetch('/api/token', { headers })
Expand Down
6 changes: 3 additions & 3 deletions docs/guide/getting-started/introduction.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Introduction

NuxtAuth is an open source Nuxt module that provides authentication for Nuxt 3+ applications. It supports multiple authentication methods, allowing you to customize the ways users login to your application.
NuxtAuth is an open source Nuxt module that provides authentication for Nuxt 4 applications. It supports multiple authentication methods, allowing you to customize the ways users login to your application.

Through a direct integration into Nuxt, you can access and utlize the user sessions within your pages, components and composables directly.

Expand Down Expand Up @@ -28,9 +28,9 @@ Through a direct integration into Nuxt, you can access and utlize the user sessi

### Why does NuxtAuth require NextAuth?

The `authjs` provider is able to provide all of its features by wrapping [Auth.js / NextAuth.js](https://github.com/nextauthjs/next-auth) under the hood. This gives the reliability & convenience of a >22.000 github star library to the Nuxt 3+ ecosystem with a native nuxt developer experience (DX). Wrapping Auth.js / NextAuth.js has the second advantage that many OAuth providers, database adapters, callbacks and more are supported out-of-the-box. This also means that you can use all NextAuth.js and Auth.js guides and documentation to achieve things with the authjs provider of nuxt-auth.
The `authjs` provider is able to provide all of its features by wrapping [Auth.js / NextAuth.js](https://github.com/nextauthjs/next-auth) under the hood. This gives the reliability & convenience of a >22.000 github star library to the Nuxt 4 ecosystem with a native nuxt developer experience (DX). Wrapping Auth.js / NextAuth.js has the second advantage that many OAuth providers, database adapters, callbacks and more are supported out-of-the-box. This also means that you can use all NextAuth.js and Auth.js guides and documentation to achieve things with the authjs provider of nuxt-auth.

NuxtAuth also provides Nuxt 3+ specific features like a convenient application-side composable to login, logout, access user-authentication data or an authentication middleware and plugin that take care of managing the user authentication lifecycle by fetching authentication data on initial load, refreshing the user authentication on re-focusing the tab and more.
NuxtAuth also provides Nuxt 4 specific features like a convenient application-side composable to login, logout, access user-authentication data or an authentication middleware and plugin that take care of managing the user authentication lifecycle by fetching authentication data on initial load, refreshing the user authentication on re-focusing the tab and more.

### What is the difference between Auth.js and NextAuth?

Expand Down
4 changes: 2 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ title: Auth

hero:
name: NuxtAuth
text: Authentication for Nuxt!
text: Authentication for Nuxt 4!
tagline: User authentication and sessions via authjs!
actions:
- theme: brand
Expand All @@ -22,7 +22,7 @@ features:
- icon:
src: /icons/Github.png
title: OAuth
details: Effortlessly connect your Nuxt 3+ application with Google, Github, Azure and countless others.
details: Effortlessly connect your Nuxt 4 application with Google, Github, Azure and countless others.
- icon:
src: /icons/Database.png
title: Use your own backend
Expand Down
2 changes: 1 addition & 1 deletion docs/recipes/introduction/welcome.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Recipes

The following pages contain recipes for commonly asked patterns, questions, and implementations. The recipes are mostly provided by the community and can serve as guidelines to implement something similar in your Nuxt 3+ application.
The following pages contain recipes for commonly asked patterns, questions, and implementations. The recipes are mostly provided by the community and can serve as guidelines to implement something similar in your Nuxt 4 application.

## What are recipes?

Expand Down
4 changes: 2 additions & 2 deletions docs/resources/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ There are some terms we use in this documentation that may not be known to every

## Module Concept

The idea of this library is to re-use all the open-source implementation that already exist in the JS ecosystem instead of rolling our own. The idea was born when researching through the ecosystem of framework-specific authentication libraries to figure out what the best implementation approach for a state-of-the-art Nuxt 3+ authentication library would be.
The idea of this library is to re-use all the open-source implementation that already exist in the JS ecosystem instead of rolling our own. The idea was born when researching through the ecosystem of framework-specific authentication libraries to figure out what the best implementation approach for a state-of-the-art Nuxt 4 authentication library would be.

During research it became clear that implementing everything from scratch will be:
- a lot of work that has already been open-sourced by others,
Expand All @@ -30,6 +30,6 @@ In our investigation we found prior attempts to make NextAuth.js framework agnos
- [NextAuth.js app examples](https://github.com/nextauthjs/next-auth/tree/main/apps)
- [Various comments, proposals, ...or this thread](https://github.com/nextauthjs/next-auth/discussions/3942), special thanks to [brillout](https://github.com/brillout) for starting the discussion, [balazsorban44](https://github.com/balazsorban44) for NextAuth.js and encouraging the discussion, [wobsoriano](https://github.com/wobsoriano) for adding PoCs for multiple languages

The main part of the work was to piece everything together, resolve some outstanding issues with existing PoCs, add new things where nothing existed yet, e.g., for the `useAuth` composable by going through the NextAuth.js client code and translating it to a Nuxt 3+ approach.
The main part of the work was to piece everything together, resolve some outstanding issues with existing PoCs, add new things where nothing existed yet, e.g., for the `useAuth` composable by going through the NextAuth.js client code and translating it to a Nuxt 4 approach.

The module had another big iteration in collaboration with [JoaoPedroAS51](https://github.com/JoaoPedroAS51) to make `useAuth` a sync operation and trigger the session lifecycle from a plugin rather than the `useAuth` composable itself.
19 changes: 9 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "1.1.1",
"license": "MIT",
"type": "module",
"description": "Authentication built for Nuxt 3! Easily add authentication via OAuth providers, credentials or Email Magic URLs!",
"description": "Authentication built for Nuxt 4! Easily add authentication via OAuth providers, credentials or Email Magic URLs!",
"homepage": "https://auth.sidebase.io",
"repository": "github:sidebase/nuxt-auth",
"engines": {
Expand Down Expand Up @@ -41,13 +41,10 @@
"test:unit": "vitest"
},
"dependencies": {
"@nuxt/kit": "^3.20.2",
"@nuxt/kit": "^4.0.0",
"defu": "^6.1.4",
"h3": "^1.15.5",
"knitwork": "^1.3.0",
"nitropack": "^2.13.1",
"requrl": "^3.0.2",
"scule": "^1.3.0",
"ufo": "^1.6.3"
},
"peerDependencies": {
Expand All @@ -61,18 +58,20 @@
"devDependencies": {
"@antfu/eslint-config": "^6.7.3",
"@nuxt/module-builder": "^1.0.2",
"@nuxt/schema": "^3.20.2",
"@nuxtjs/eslint-config-typescript": "^12.1.0",
"@nuxt/schema": "^4.0.0",
"@nuxt/eslint": "^1.7.1",
"@types/node": "^20.19.29",
"eslint": "^9.39.2",
"nuxt": "^3.20.2",
"nuxt": "^4.0.0",
"ofetch": "^1.5.1",
"oxlint": "^1.39.0",
"ts-essentials": "^9.4.2",
"ts-essentials": "^10.1.1",
"typescript": "^5.8.3",
"vitepress": "^1.6.4",
"vitest": "^3.2.4",
"vue-tsc": "^2.2.12"
"vue-tsc": "^2.0.21",
"vite": "^7.0.0",
"nitropack": "^2.11.13"
},
"packageManager": "pnpm@10.15.0+sha512.486ebc259d3e999a4e8691ce03b5cac4a71cbeca39372a9b762cb500cfdf0873e2cb16abe3d951b1ee2cf012503f027b98b6584e4df22524e0c7450d9ec7aa7b"
}
2 changes: 1 addition & 1 deletion playground-authjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"postinstall": "nuxt prepare"
},
"devDependencies": {
"nuxt": "^3.20.2",
"nuxt": "^4.0.0",
"typescript": "^5.8.3",
"vue-tsc": "^2.2.12"
}
Expand Down
Loading