Skip to content

Commit

Permalink
docs: Make 0.6.0 docs main documentation (#566)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoey-kaiser authored Nov 13, 2023
1 parent 7af1244 commit 7e65486
Show file tree
Hide file tree
Showing 72 changed files with 1,294 additions and 1,294 deletions.
119 changes: 88 additions & 31 deletions docs/content/1.getting-started/1.index.md
Original file line number Diff line number Diff line change
@@ -1,54 +1,112 @@
---
description: "Introduction to `nuxt-auth` and its features as an authentication module for your Vue / Nuxt 3 application."
description: "Introduction to `nuxt-auth` and its features as an authentication module for your Vue / Nuxt 3 application: authentication for static- and non-static Nuxt 3 applications."
---

# Introduction

::alert{type="info"}
[Checkout the `0.6`-docs](/nuxt-auth/v0.6/getting-started) if you want to get get started with the `local`-provider or have a static Nuxt application.
These are the docs for the experimental v0.6 version of `nuxt-auth` with static Nuxt 3 and `local` provider support. [Checkout the `0.5`-docs](/nuxt-auth/getting-started) for the nuxt-auth-version <=0.5.
::

`nuxt-auth` is an open source Nuxt module that provides authentication for non-static Nuxt 3 applications.
`nuxt-auth` is an open source Nuxt module that provides authentication for Nuxt 3 applications.

The easiest way to get started with `nuxt-auth` is using [the sidebase Merino stack](/sidebase):
::code-group
```bash [npm]
npm create sidebase@latest
```
```bash [pnpm]
pnpm create sidebase@latest
```
```bash [yarn]
# Note: Due to a known problem with `yarn`, it is not possible to force yarn to always use `@latest`: https://github.com/yarnpkg/yarn/issues/6587
yarn create sidebase
```
`nuxt-auth` supports the following:
::list{type="success"}
- `useAuth` composable to perform authentication-related actions from the application
- global- and local-application middleware to protect application-pages
- guest-mode to only allows guest to see certain pages (e.g.: the login page)
- authentication-backend setup for the `authjs`-auth-provider
- static Nuxt 3 apps with the `local`-auth-provider
- documentation, recipes and example code to get you started
::
This will create a Nuxt 3 project with `nuxt-auth` already setup & working.

`nuxt-auth` supports three main types of authentication out of the box:
`nuxt-auth` employs 2 providers to facilitate the act of authenticating a user:
::list{type="success"}
- OAuth: Authentication via third-party OAuth providers like Google, Azure, Github, Discord, ...
- Credentials: Authentication via a username and password that the user supplies and custom logic that you implement yourself
- Emails: Authentication via "Magic URL" emails, like Slack or Notion
- `local`: Username and password authentication. `local` expects the endpoint to return a token that can be used to authenticate subsequent requests
- `authjs`: A `authjs` (`next-auth`) based provider that supports most OAuth- and Magic-URL sign-ins (think Slack or Notion). This provider also supports username and password based sign-in, but discourages from using it
::

`nuxt-auth` is able to provide the above and more (like database adapters, callback hooks, ...) by wrapping [NextAuth.js](https://github.com/nextauthjs/next-auth) under the hood. This gives the reliability & convenience of a >12.000 github star library to the Nuxt 3 ecosystem with a native nuxt developer experience (DX). Wrapping `NextAuth.js` has the second advantage that many OAuth providers, database adapters, callbacks and more are supported out-of-the-box. This means that whenever you want to achieve something within the `NuxtAuthHandler` you can use all NextAuth guides and documentation to do so - the authentication handlers behave identical.

`nuxt-auth` 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.
Other libraries / modules would call these authentication-schemes, backends or maybe even strategys.

::callout
#summary
Show me the code!

#content
Visit the [quick start](/nuxt-auth/getting-started/quick-start) page to see code examples.
Visit the [quick start](/nuxt-auth/v0.6/getting-started/quick-start) page to see code examples.

Checkout the example `nuxt-auth` app: https://nuxt-auth-example.sidebase.io/

Here's the source-code https://github.com/sidebase/nuxt-auth-example of the example app.
::

## Authentication providers
## Which Provider should I pick?

To pick a provider you will first have to take into consideration the requirements of your use-case. Below is a small table to help you pick:

| | authjs | local |
|----------------------------------------------------------- |-------------------------------------: |------: |
| **Authentication Methods** | | |
| OAuth | ✅ (>50 providers) ||
| Magic URLs |||
| Credential / Username + Password flow | 🚧 (if possible: use `local` instead) ||
| | | |
| **Features** | | |
| app `useAuth`-composable to sign-in, sign-out, ... |||
| session-management: auto-refresh, refresh on refocus, ... |||
| static apps ("nuxi generate") |||
| guest mode |||
| app-side middleware |||
| server-side middleware |||
| pre-made login-page | ✅ (impacts bundle-size) ||
| database-adapters, server-side callback-hooks |||

In general one can say that picking:
- `authjs` is best suited for plug-and-play OAuth for established oauth-providers or magic-url based sign-ins
- `local` is best when you already have a backend that accepts username + password as a login or want to build a static application

### `authjs` Remarks

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 >12.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`.

`nuxt-auth` 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.

In the future a separate OAuth provider for static apps may be added, read the next section for more on this.

#### Auth.js vs next-auth

We use `authjs` everywhere to mean `authjs` and `next-auth` interchangably as `next-auth` is currently transitioning to become `authjs` (branded name: `Auth.js`), see [the announcement here](https://twitter.com/balazsorban44/status/1603082914362986496).

We are following this transition and are changing code related to this as it becomes stable enough to use it. You can follow our implementation of this transition [in this issue](https://github.com/sidebase/nuxt-auth/v0.6/issues/117). If you are googling anything related to this provider, we recommend that you still use the term `next-auth` as this is still the mainly used library and the stable one we mostly use under the hood. New features that are `Auth.js` only are _not_ guaranteed to work at the moment, as we still mostly rely on next-auth as a stable foundation.

### `local` Remarks

The `local` provider is based on [the local schema of the Nuxt 2 nuxt-auth module](https://auth.nuxtjs.org/schemes/local). It was added in v0.6.0 of `nuxt-auth` and serves as a starting point to add further static providers like [cookie based](https://auth.nuxtjs.org/schemes/cookie) authentication, support for [refresh tokens](https://auth.nuxtjs.org/schemes/refresh) and [static OAuth support](https://auth.nuxtjs.org/schemes/oauth2).

The `local` provider works by receiving an authentication token from the backend it send a `username` and `password` to. This could for example be a JWT token. The `local` provider then stores this token and makes it accessible to you for use. The `local` provider will also fetch user / session information from the backend once it has successfully logged in.

Any help with this effort is very welcome! Feel free to open an issue or a PR to add support for further providers 💘.

## Starting with sidebase

The easiest way to get started with `nuxt-auth` is using [the sidebase Merino stack](/sidebase):
::code-group
```bash [npm]
npm create sidebase@latest
```
```bash [pnpm]
pnpm create sidebase@latest
```
```bash [yarn]
# Note: Due to a known problem with `yarn`, it is not possible to force yarn to always use `@latest`: https://github.com/yarnpkg/yarn/issues/6587
yarn create sidebase
```
::
This will create a Nuxt 3 project with `nuxt-auth` already setup & working.

## Feature Collection

### Authentication providers

::list{type="success"}
- OAuth (e.g., Github, Google, Twitter, Azure, ...)
Expand All @@ -57,26 +115,25 @@ Here's the source-code https://github.com/sidebase/nuxt-auth-example of the exam
- Email Magic URLs
::

## Application Side Session Management
::alert{type="info"}
Prior to v0.5.0 `useAuth()` was called `useSession()`.
::
### Application Side Session Management

::list{type="success"}
- composable `const { signIn, signOut, status, data, lastRefreshedAt, ... } = useAuth()`
- Auto-refresh the session periodically
- Auto-refresh the session on tab-refocus
- Efficient session fetching: One time on page load, afterwards for specific actions (e.g., on navigation)
- Full typescript support for all methods and properties
- Guest-Mode
::

## Application Protection
### Application Protection

::list{type="success"}
- Application-side middleware protection either for the full application or specific pages
- Server-side middleware and endpoint protection
::

## REST API
### REST API (authjs only)

::list{type="success"}
- `GET /signin`,
Expand Down
14 changes: 12 additions & 2 deletions docs/content/1.getting-started/2.installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ pnpm i -D @sidebase/nuxt-auth
::

::alert{type="info"}
Note that we try our best to keep `nuxt-auth` stable, but it is also a young module that is in active development. If you want to be extra sure nothing breaks, you should pin the patch version, e.g., by using `--save-exact` when running the install command.
Note that we try our best to keep `nuxt-auth` stable, but it is also a fresh module that is in active development. If you want to be extra sure nothing breaks, you should pin the patch version, e.g., by using `--save-exact` when running the install command.
::

`nuxt-auth` has `next-auth` as a peer-dependency. With all package managers except `npm` you must install the peer dependency alongside `nuxt-auth`:
## Specifics: `authjs`-Provider

If you want to use the `authjs` provider, you have to install `next-auth`. With all package managers except `npm` you must manually install the peer dependency alongside `nuxt-auth`:
::code-group
```bash [yarn]
yarn add [email protected]
Expand All @@ -33,6 +35,14 @@ pnpm i [email protected]

You can find all available `next-auth` versions [on npm](https://www.npmjs.com/package/next-auth?activeTab=versions). You do not need to install any other peer-dependencies in order to use `nuxt-auth`.

If you are unsure which provider to choose, have a look at the [overview on the getting-started page](/nuxt-auth/v0.6/getting-started#which-provider-should-i-pick).

## Specifics: `local`-Provider

The `local` provider does not have any specific extra dependencies. However, you will need to make sure that you have a backend somewhere that provides username + password based authentication, [read more about this on the quick-start page](/nuxt-auth/v0.6/getting-started/quick-start).

If you are unsure which provider to choose, have a look at the [overview on the getting-started page](/nuxt-auth/v0.6/getting-started#which-provider-should-i-pick).

## Requirements

`nuxt-auth` only needs Nuxt 3 to run. In the future Nuxt 2 or Nuxt Bridge may be supported.
82 changes: 73 additions & 9 deletions docs/content/1.getting-started/3.quick-start.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
# Quick Start

After [installing the package](/nuxt-auth/getting-started/installation), add the package to your `nuxt.config.ts`:

```ts
After [following the installation-steps](/nuxt-auth/v0.6/getting-started/installation), add `@sidebase/nuxt-auth` to your `nuxt.config.ts` and specify the provider-type you want to use:
::code-group
```ts [authjs]
export default defineNuxtConfig({
modules: ['@sidebase/nuxt-auth'],
modules: ['@sidebase/nuxt-auth'],
auth: {
provider: {
type: 'authjs'
}
}
})
```
```ts [local]
export default defineNuxtConfig({
modules: ['@sidebase/nuxt-auth'],
auth: {
provider: {
type: 'local'
}
}
})
```
::

Then create the authentication handler (`NuxtAuthHandler`) that will expose the API endpoints for handling all authentication-related requests and add at least one [authentication provider](https://next-auth.js.org/providers/):
Then continue with the provider-specific steps below.

## Provider-specific Steps

### Provider: `authjs`

After the `nuxt.config.ts` setup from above you have to create the authentication handler (`NuxtAuthHandler`) that will setup the backend and expose the API endpoints for handling all authentication-related requests and add at least one [authentication provider](https://next-auth.js.org/providers/):

```ts
// file: ~/server/api/auth/[...].ts
Expand All @@ -26,11 +48,53 @@ export default NuxtAuthHandler({
})
```

That's it! You can now use all user-related functionality, for example:
### Provider: `local`

The local provider does not require any additional steps, as it relies on an already existing backend. By default, the `local` provider will try to reach this backend using the following default-configuration:
```ts
{
baseURL: '/api/auth',
endpoints: {
signIn: { path: '/login', method: 'post' },
signOut: { path: '/logout', method: 'post' },
signUp: { path: '/register', method: 'post' },
getSession: { path: '/session', method: 'get' }
}
}
```

So when you call the `signIn` method, the endpoint `/api/auth/login` will be hit with the `username` and `password` you pass as a body-payload. You likely have to modify these parameters to fit to your backend - you can adjust these parameters in your `nuxt.config.ts` using the options [specified here](/nuxt-auth/v0.6/configuration/nuxt-config).

Note: The backend can also be in the same Nuxt 3 application, e.g., have a look at this example in the `nuxt-auth` repository:
- [full nuxt app](https://github.com/sidebase/nuxt-auth/tree/main/playground-local)
- its [backend](https://github.com/sidebase/nuxt-auth/tree/main/playground-local/server/api/auth)
- its [`nuxt.config.ts`](https://github.com/sidebase/nuxt-auth/blob/main/playground-local/nuxt.config.ts)

::alert{type="info"}
Prior to v0.5.0 `useAuth()` was called `useSession()`.
The linked example-implementation only serves as a starting-point and is not considered to be secure.
::

The backend musst accept a request with a body like:
```ts
{
username: '[email protected]',
password: 'hunter2'
}
```

and return a token that can be used to authenticate future requests in the response body, e.g., like:
```ts
{
tokens: {
accessToken: 'eyBlaBlub'
}
}
```

## Finishing up

That's it! You can now use all user-related functionality, for example:

::code-group
```ts [Application side]
// file: e.g ~/pages/login.vue
Expand All @@ -42,7 +106,7 @@ data.value // Session data, e.g., expiration, user.email, ...
await signIn() // Sign in the user
await signOut() // Sign out the user
```
```ts [Server side]
```ts [authjs: Server side]
// file: e.g: ~/server/api/session.get.ts
import { getServerSession } from '#auth'

Expand All @@ -56,4 +120,4 @@ export default eventHandler(async (event) => {
```
::

To learn how to protect pages read [about the application-side usage](/nuxt-auth/application-side), to learn how to protect server-routes and API endpoints read [about the server-side usage](/nuxt-auth/server-side).
To learn how to protect pages read [about the application-side usage](/nuxt-auth/v0.6/application-side), to learn how to protect server-routes and API endpoints read [about the server-side usage](/nuxt-auth/v0.6/server-side). You can also find more provider-specific information on these pages.
10 changes: 8 additions & 2 deletions docs/content/1.getting-started/4.getting-help.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ At some point, you may find that there's an issue you need some help with.

But don't worry! We're a friendly community of developers and we'd love to help. Concretely this means to:
- Checkout the docs (page that you are currently viewing),
- Search open issues and discussions: https://github.com/sidebase/nuxt-auth/issues
- Search open & resolved issues and discussions: https://github.com/sidebase/nuxt-auth/v0.6/issues
- Hop on Discord to ask us directly: https://discord.gg/VzABbVsqAc,
- Open an issue to file a bug, ask for an enhancement or get an answer to a question: https://github.com/sidebase/nuxt-auth/issues/new/choose
- Open an issue to file a bug, ask for an enhancement or get an answer to a question: https://github.com/sidebase/nuxt-auth/v0.6/issues/new/choose

We aim to follow the getting-help standards of the nuxt-project as described here and ask you to do the same when opening an issue or pinging us for help: https://nuxt.com/docs/community/getting-help#getting-help.

## Minimal Reproductions

When resolving a bug a minimal reproduction is almost always required, [read on the official nuxt.com page how to create one](https://nuxt.com/docs/community/reporting-bugs#create-a-minimal-reproduction).

Note that your reproduction should also work outside of providers like stackblitz. The reason for this is that stackblitz (and likely other, similar providers) do not properly support cookies, which are essential for `nuxt-auth` to work.
Loading

0 comments on commit 7e65486

Please sign in to comment.