### Development and Production Commands
Source: https://github.com/nuxt-modules/supabase/blob/main/demo/README.md
Commands to start the development server or build the application for production.
```bash
pnpm dev
```
```bash
pnpm build
```
--------------------------------
### Install Dependencies
Source: https://github.com/nuxt-modules/supabase/blob/main/demo/README.md
Install the required project dependencies using pnpm.
```bash
pnpm i
```
--------------------------------
### Add Supabase Module Dependency
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Install the @nuxtjs/supabase module as a dev dependency using the Nuxt CLI.
```bash
npx nuxi@latest module add supabase
```
--------------------------------
### Fetch Supabase User from API Route in Vue Component (Vue.js)
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/4.serverSupabaseUser.md
This example shows how to call a server API route (e.g., '/api/me') from a Vue component to fetch Supabase user data. It uses `$fetch` to make the request and stores the result in a reactive reference. This is suitable for client-side rendering or initial data fetching.
```javascript
const user = ref(null)
const fetchMe = async () => {
user.value = await $fetch('/api/me')
}
```
--------------------------------
### Realtime data subscription and refresh
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseClient.md
Listens for changes in the 'collaborators' table using Supabase Realtime and refreshes the data when an event occurs. Includes setup and cleanup for the subscription.
```vue
import type { RealtimeChannel } from '@supabase/supabase-js'
const client = useSupabaseClient()
let realtimeChannel: RealtimeChannel
// Fetch collaborators and get the refresh method provided by useAsyncData
const { data: collaborators, refresh: refreshCollaborators } = await useAsyncData('collaborators', async () => {
const { data } = await client.from('collaborators').select('name')
return data
})
// Once page is mounted, listen to changes on the `collaborators` table and refresh collaborators when receiving event
onMounted(() => {
// Real time listener for new workouts
realtimeChannel = client.channel('public:collaborators').on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'collaborators' },
() => refreshCollaborators()
)
realtimeChannel.subscribe()
})
// Don't forget to unsubscribe when user left the page
onUnmounted(() => {
client.removeChannel(realtimeChannel)
})
```
--------------------------------
### Nuxt Supabase Email Login Example
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/index.md
This Vue.js snippet demonstrates how to implement an email-based login functionality using Supabase in a Nuxt 3 application. It utilizes the `useSupabaseClient` composable to interact with Supabase authentication and `ref` for managing the email input state. The function `signInWithOtp` sends a magic link to the provided email address.
```vue
```
--------------------------------
### Get Supabase User in Nuxt Server Route (TypeScript)
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/4.serverSupabaseUser.md
This snippet demonstrates how to define a Nuxt server API route that retrieves the Supabase user object using the `serverSupabaseUser` function. It takes the event object as input and returns the user data. This requires the `#supabase/server` module to be installed and configured.
```typescript
import { serverSupabaseUser } from '#supabase/server'
export default defineEventHandler(async (event) => {
return await serverSupabaseUser(event)
})
```
--------------------------------
### Implementing Auth Middleware with useSupabaseUser
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseUser.md
Provides an example of creating a custom Nuxt route middleware that utilizes useSupabaseUser to protect routes, redirecting unauthenticated users to a login page.
```typescript
export default defineNuxtRouteMiddleware((to, _from) => {
const user = useSupabaseUser()
if (!user.value) {
return navigateTo('/login')
}
})
```
```typescript
definePageMeta({
middleware: 'auth'
})
```
--------------------------------
### Accessing Supabase User in Vue Components
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseUser.md
Demonstrates how to import and use the useSupabaseUser composable to retrieve the current authenticated user's data within a Vue component's script setup.
```vue
```
--------------------------------
### Access User Session in Vue Components
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseSession.md
Demonstrates how to use the useSupabaseSession composable to retrieve the current user session within a Vue component's setup script.
```vue
```
--------------------------------
### Supabase Confirm Page with Basic Redirect - Vue
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/2.authentication.md
This Vue component serves as the confirmation page after a user attempts to log in via Supabase. It uses `useSupabaseUser` to watch for authentication state changes. Once a user is detected, it automatically redirects them to the home page. This setup assumes default redirect behavior.
```vue
Waiting for login...
```
--------------------------------
### Compare auth.getUser and auth.getClaims payloads
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/4.migration.md
The return type of useSupabaseUser has changed from the full User object to a JWT Claims object. Use these examples to identify missing fields like identities or last_sign_in_at in your application logic.
```json
{
id: "11111111-1111-1111-1111-111111111111",
aud: "authenticated",
role: "authenticated",
email: "example@email.com",
email_confirmed_at: "2024-01-01T00:00:00Z",
phone: "",
confirmed_at: "2024-01-01T00:00:00Z",
last_sign_in_at: "2024-01-01T00:00:00Z",
app_metadata: {},
user_metadata: {},
identities: []
}
```
```json
{
session_id: "11111111-1111-1111-1111-111111111111",
sub: "11111111-1111-1111-1111-111111111111",
aud: "authenticated",
role: "authenticated",
email: "example@email.com",
aal: "aal1",
amr: [],
exp: 1715769600,
iat: 1715766000,
is_anonymous: false,
iss: "https://project-id.supabase.co/auth/v1",
phone: "+13334445555",
app_metadata: {},
user_metadata: {},
// identities is missing
// last_sign_in_at is missing
// confirmed_at is missing
// email_confirmed_at is missing
}
```
--------------------------------
### Configure Supabase environment variables
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/4.migration.md
Define the public and secret keys in your .env file to authenticate with Supabase.
```bash
NUXT_PUBLIC_SUPABASE_KEY=
NUXT_SUPABASE_SECRET_KEY=
```
--------------------------------
### Set Supabase Environment Variables
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Configure your Supabase URL and publishable key using environment variables in your .env file. Using the NUXT_ prefix is recommended for runtime configuration.
```bash
NUXT_PUBLIC_SUPABASE_URL="https://example.supabase.co"
NUXT_PUBLIC_SUPABASE_KEY=""
```
--------------------------------
### Configure Environment Variables
Source: https://github.com/nuxt-modules/supabase/blob/main/demo/README.md
Required environment variables for Supabase integration in the .env file.
```text
NUXT_PUBLIC_SUPABASE_URL="https://example.supabase.co"
NUXT_PUBLIC_SUPABASE_KEY=""
```
--------------------------------
### Initialize Service Role Client in Server Route
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/2.serverSupabaseServiceRole.md
Use this in server routes to perform database operations with elevated permissions. Requires NUXT_SUPABASE_SECRET_KEY to be configured in the environment.
```ts
import { serverSupabaseServiceRole } from '#supabase/server'
export default eventHandler(async (event) => {
const client = serverSupabaseServiceRole(event)
const { data } = await client.from('rls-protected-table').select()
return { sensitiveData: data }
})
```
--------------------------------
### Initialize Supabase Client in Server Route
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/1.serverSupabaseClient.md
Demonstrates how to import and use serverSupabaseClient within a Nuxt server route to query data from a Supabase table. The function is asynchronous and requires the event object to initialize.
```typescript
import { serverSupabaseClient } from '#supabase/server'
export default eventHandler(async (event) => {
const client = await serverSupabaseClient(event)
const { data } = await client.from('libraries').select('*')
return { libraries: data }
})
```
--------------------------------
### Create Tasks Table
Source: https://github.com/nuxt-modules/supabase/blob/main/demo/README.md
SQL query to initialize the tasks table in the Supabase SQL Editor.
```sql
CREATE TABLE tasks (
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
"user" UUID NOT NULL,
title TEXT,
completed BOOLEAN DEFAULT FALSE
);
```
--------------------------------
### Supabase Client Options
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Allows customization of the Supabase client initialization. When `useSsrCookies` is active, these options merge with `@supabase/ssr` settings, and some may be restricted.
```typescript
clientOptions: {
auth: {
flowType: 'pkce',
autoRefreshToken: isBrowser(),
detectSessionInUrl: isBrowser(),
persistSession: true,
},
}
```
--------------------------------
### Handling Post-Login Redirects in Vue
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseCookieRedirect.md
Demonstrates how to use the useSupabaseCookieRedirect composable within a Vue component to detect user login and navigate to a previously saved path.
```vue
```
--------------------------------
### Sign in and Sign out with OAuth
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseClient.md
Handles user authentication using GitHub OAuth and signing out. Ensure your redirect URL is correctly configured.
```typescript
const supabase = useSupabaseClient()
const signInWithOAuth = async () => {
const { error } = await supabase.auth.signInWithOAuth({
provider: 'github',
options: {
redirectTo: 'http://localhost:3000/confirm',
},
})
if (error) console.log(error)
}
const signOut = async () => {
const { error } = await supabase.auth.signOut()
if (error) console.log(error)
}
```
--------------------------------
### Manual Redirect Path Management
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseCookieRedirect.md
Shows how to manually set, read, and clear redirect paths using the useSupabaseCookieRedirect composable outside of a standard watch pattern.
```typescript
const redirectInfo = useSupabaseCookieRedirect()
// Save a specific path
redirectInfo.path.value = '/dashboard'
// Read the current path without clearing it
const currentPath = redirectInfo.path.value
// Get the path and clear it
const path = redirectInfo.pluck()
```
--------------------------------
### Generate TypeScript Types (Live Database)
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Command to generate Supabase TypeScript definitions from a live database. The output is piped to a file within the Nuxt source directory.
```bash
supabase gen types --lang=typescript --project-id YourProjectId > app/types/database.types.ts
```
--------------------------------
### Generate TypeScript Types (Local Environment)
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Command to generate Supabase TypeScript definitions using a local Supabase environment. The output is directed to a specified file.
```bash
supabase gen types --lang=typescript --local > app/types/database.types.ts
```
--------------------------------
### Fetch Session Data in Vue Components
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/3.serverSupabaseSession.md
Shows how to fetch the session data from the previously defined API route using $fetch or useFetch, including necessary header configuration for SSR.
```typescript
const session = ref(null)
const fetchSession = async () => {
session.value = await $fetch('/api/session')
}
```
```typescript
const session = ref(null)
const { data } = await useFetch('/api/session', {
headers: useRequestHeaders(['cookie'])
})
session.value = data
```
--------------------------------
### Auth Middleware Implementation
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseSession.md
How to protect routes using custom Nuxt middleware with useSupabaseSession.
```APIDOC
## Custom Auth Middleware
### Description
Create a custom middleware to protect specific routes by checking the session value.
### Implementation
```ts
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to, _from) => {
const session = useSupabaseSession()
if (!session.value) {
return navigateTo('/login')
}
})
```
### Usage in Page
```ts
// pages/dashboard.vue
definePageMeta({
middleware: 'auth'
})
```
```
--------------------------------
### Apply Middleware to Pages
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseSession.md
Illustrates how to apply the custom authentication middleware to a specific page using the definePageMeta function.
```typescript
definePageMeta({
middleware: 'auth'
})
```
--------------------------------
### Fetch data from Supabase with useAsyncData
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseClient.md
Fetches specific data from the 'restaurants' table using the Supabase client and Nuxt's useAsyncData composable. Ensures data is fetched efficiently.
```vue
const client = useSupabaseClient()
const { data: restaurant } = await useAsyncData('restaurant', async () => {
const { data } = await client.from('restaurants').select('name, location').eq('name', 'My Restaurant Name').single()
return data
})
```
--------------------------------
### Configure Supabase Module Options
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Customize Supabase module behavior by defining options within the 'supabase' key in your nuxt.config.ts.
```typescript
export default defineNuxtConfig({
// ...
supabase: {
// Options
}
})
```
--------------------------------
### Supabase Login Page with Email OTP - Vue
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/2.authentication.md
This Vue component demonstrates how to initiate a Supabase sign-in flow using email and One-Time Password (OTP). It utilizes the `useSupabaseClient` composable to interact with Supabase Auth and requires an email input and a button to trigger the OTP sending process. The `emailRedirectTo` option is crucial for specifying the confirmation page URL.
```vue
```
--------------------------------
### Manually pass Database typings to the client
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseClient.md
Manually provides Database typings to the Supabase client by importing the 'Database' type.
```vue
import type { Database } from '~/types'
const client = useSupabaseClient()
```
--------------------------------
### Retrieve Supabase Session in Server Route
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/3.serverSupabaseSession.md
Demonstrates how to import and use serverSupabaseSession within a Nuxt server API route to return the current session object.
```typescript
import { serverSupabaseSession } from '#supabase/server'
export default defineEventHandler(async (event) => {
return await serverSupabaseSession(event)
})
```
--------------------------------
### Fetch Data from API Route in Vue
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/1.serverSupabaseClient.md
Shows how to consume the previously created server API route from a Vue component using $fetch or useFetch. When performing SSR, it is necessary to pass the request headers to ensure authentication cookies are included.
```typescript
const fetchLibrary = async () => {
const { libraries } = await $fetch('/api/libraries')
}
const { data: { libraries }} = await useFetch('/api/libraries', {
headers: useRequestHeaders(['cookie'])
})
```
--------------------------------
### useSupabaseCookieRedirect Composable
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseCookieRedirect.md
This composable helps manage redirect paths using cookies, allowing you to save and retrieve a user's intended destination after login. It can be used automatically via configuration or manually.
```APIDOC
## useSupabaseCookieRedirect
### Description
Provides a composable to store and retrieve a redirect path using cookies. This is useful for redirecting users to the page they previously tried to visit after they log in.
### Method
Composable function
### Endpoint
N/A (Client-side composable)
### Parameters
None directly for the composable itself. Configuration is done via runtime config.
### Request Example
```vue
```
### Response Values
- `path` (Ref) - A reactive cookie reference for the redirect path. Can be read and written to.
- `pluck()` - A function that returns the current redirect path and clears it from the cookie.
### Manual Usage Example
```ts
const redirectInfo = useSupabaseCookieRedirect()
// Save a specific path
redirectInfo.path.value = '/dashboard'
// Read the current path without clearing it
const currentPath = redirectInfo.path.value
// Get the path and clear it
const path = redirectInfo.pluck()
```
### Notes
The cookie is saved with the name `{cookiePrefix}-redirect-path` where `cookiePrefix` is defined in the runtime config.
```
--------------------------------
### Create Custom Auth Middleware
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseSession.md
Shows how to define a custom Nuxt route middleware that checks for an active session and redirects unauthenticated users to the login page.
```typescript
export default defineNuxtRouteMiddleware((to, _from) => {
const session = useSupabaseSession()
if (!session.value) {
return navigateTo('/login')
}
})
```
--------------------------------
### Fetch Supabase User with SSR and Cookies (Vue.js)
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/4.serverSupabaseUser.md
This snippet illustrates how to fetch Supabase user data from an API route during Server-Side Rendering (SSR) in a Nuxt application. It utilizes `useFetch` and includes the necessary 'cookie' header to pass authentication tokens, ensuring the user is correctly identified on the server. This is crucial for maintaining user sessions across SSR requests.
```javascript
const user = ref(null)
const { data } = await useFetch('/api/me', {
headers: useRequestHeaders(['cookie'])
})
user.value = data
```
--------------------------------
### Fetch Data from API Route in Vue
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/3.services/2.serverSupabaseServiceRole.md
Call the protected server route from a Vue component using useFetch.
```ts
const fetchSensitiveData = async () => {
const { sensitiveData } = await useFetch('/api/bypass-rls')
}
```
--------------------------------
### Default Redirect Options
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Configures user redirection for authentication states like login, callback, and route inclusion/exclusion. `saveRedirectToCookie` can store the user's intended path.
```typescript
redirectOptions: {
login: '/login',
callback: '/confirm',
include: undefined,
exclude: [],
saveRedirectToCookie: false,
}
```
--------------------------------
### Cookie Options for Token Sharing
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Sets options for cookies used to share authentication tokens between server and client. Note that `maxAge` here does not dictate the Supabase session lifetime.
```typescript
cookieOptions: {
maxAge: 60 * 60 * 8,
sameSite: 'lax',
secure: true
}
```
--------------------------------
### Supabase Confirm Page with Cookie Redirect - Vue
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/2.authentication.md
This Vue component enhances the confirmation page by handling redirects to the originally requested page after login. It utilizes `useSupabaseCookieRedirect` and the `saveRedirectToCookie` option (enabled in module configuration) to store and retrieve the intended destination. Upon successful login, it retrieves the path from the cookie and redirects the user, falling back to the home page if no path is found.
```vue
Waiting for login...
```
--------------------------------
### Generate Supabase TypeScript types
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseClient.md
Generates TypeScript types for your Supabase database. Use the '--project-id' flag for live databases or '--local' for local development environments.
```shell
## Generate types from live database
supabase gen types typescript --project-id YourProjectId > app/types/database.types.ts
## Generate types when using local environment
supabase gen types typescript --local > app/types/database.types.ts
```
--------------------------------
### Configure Supabase Module in nuxt.config.ts
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/1.introduction.md
Add the @nuxtjs/supabase module to the modules array in your nuxt.config.ts file.
```typescript
export default defineNuxtConfig({
modules: ['@nuxtjs/supabase'],
})
```
--------------------------------
### Listen for Password Recovery Events
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/2.authentication.md
Uses onAuthStateChange to monitor for the PASSWORD_RECOVERY event. This allows the application to trigger specific logic, such as automatic password updates, when a user clicks the recovery link.
```vue
```
--------------------------------
### Request Password Reset Email
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/2.authentication.md
Initiates the password recovery flow by sending a reset link to the user's email address. It uses the Supabase client's resetPasswordForEmail method and requires a redirect URL for the update page.
```vue
```
--------------------------------
### useSupabaseSession Composable
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/2.composables/useSupabaseSession.md
Access the current authenticated user's session object within a Vue component.
```APIDOC
## useSupabaseSession
### Description
Returns the current Supabase session object. If the user is not logged in, it returns null.
### Usage
```vue
```
### Returns
- **session** (Ref) - The current Supabase session object.
```
--------------------------------
### Update User Password
Source: https://github.com/nuxt-modules/supabase/blob/main/docs/content/1.getting-started/2.authentication.md
Updates the user's password after they have been redirected to the application. This function calls updateUser on the Supabase auth client with the new password value.
```vue
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.