@maximilian-schwarz/nhost v0.0.6
Nuxt Nhost
A simple wrapper around nhost-js to enable usage and integration within Nuxt.
- Nuxt 3 ready
- Vue 3 composables
- Nhost-js V2
- Usage in API server routes
- Authentication support
- TypeScript support
Overview
Introduction
@uniqueweb/nhost is a Nuxt module for first class integration with Nhost. Checkout the Nuxt 3 documentation and Nhost to learn more.
Installation
Add @uniqueweb/nhost dev dependency to your project:
npm install @maximilian-schwarz/nhost --save-dev
yarn add --dev @maximilian-schwarz/nhost
Lastly, add NUXT_PUBLIC_NHOST_SUBDOMAIN and NUXT_PUBLIC_NHOST_REGION to the .env:
NUXT_PUBLIC_NHOST_SUBDOMAIN=""
NUXT_PUBLIC_NHOST_REGION=""
Options
You can configure the nhost module by using the nhost key in nuxt.config.{ts,js}
:
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
// ...
nhost: {
// Options
}
}
backendUrl
Default: string
''
The unique Nhost BACKEND_URL which is supplied when you create a new project in your project dashboard.
subdomain
Default: string
process.env.NHOST_SUBDOMAIN
(e.g. ieingiwnginwnfnegqwvdqwdwq)
The unique Nhost subdomain which is supplied when you create a new project in your project dashboard.
region
Default: string
process.env.NHOST_REGION
(e.g. eu-central-1)
The unique Nhost region which is supplied when you create a new project in your project dashboard.
adminSecret
Default: string
''
When set, the admin secret is sent as a header, x-hasura-admin-secret, for all requests to GraphQL, Storage, and Serverless Functions.
cookie
Default: object
{
name: 'nhost',
lifetime: 60 * 60 * 8,
domain: '',
path: '/',
sameSite: 'lax'
}
The cookie settings to handle authentication state
Usage
Vue composables
Auto-import your client inside your vue files.
useNhostClient
This composable is using nhost-js under the hood, it gives acces to the Nhost client.
<script setup>
const client = useNhostClient()
// Example: client.auth
// Example: client.storage
// Example: client.functions
// Example: client.graphql
</script>
SignIn
Check Nhost Documentation for further details.
<template>
<div>
<form @submit.prevent="login">
<input v-model="email" type="email">
<input v-model="password" type="password">
<button type="submit">
Login
</button>
</form>
</div>
</template>
<script setup>
const { auth } = useNhostClient()
const email = useState('email', () => '')
const password = useState('password', () => '')
const login = async () => {
await auth.signIn({
email: email.value,
password: password.value
})
}
</script>
SignOut
Check Nhost Documentation for further details.
<template>
<button @click="logout">Logout</button>
</template>
<script setup>
const { auth } = useNhostClient()
const logout = async () => {
await auth.signOut()
}
</script>
useNhostUser
Once logged in, you can auto-import your user everywhere inside your vue files.
<script setup>
const user = useNhostUser()
</script>
Auth middleware
You can protect your authenticated routes by creating a custom middleware in your project, here is an example:
export default defineNuxtRouteMiddleware((to, _from) => {
const user = useNhostUser()
if (!user.value) {
return navigateTo('/login')
}
})
Then you can reference your middleware in your page with:
definePageMeta({
middleware: 'auth'
})
Learn more about Nuxt middleware and definePageMeta.
Server services
serverNhostClient
This function is working similary as the useNhostClient composable but is designed to be used in server routes.
Define your server route and just import the serverNhostClient from @nhost/server
.
server/api/customers.ts
import { serverNhostClient } from '@nhost/server'
export default defineEventHandler(async (event) => {
const client = await serverNhostClient(event)
const CUSTOMERS = gql`
query {
customers {
id
name
}
}
`
const { data, error } = await client.graphql.request(CUSTOMERS)
return { customers: data }
})
Then call your API route from any vue file:
const fetchCustomer = async () => {
const { customers } = await $fetch('/api/customers')
}
Be careful, if you want to call this route on SSR, please read this section, you must send your browser cookies including your nhost token.
const { data: { customers }} = await useFetch('/api/customers', {
headers: useRequestHeaders(['cookie'])
})
serverNhostAdminSecret
This function is designed to work only in server routes, there is no vue composable equivalent. It works similary as the serverNhostClient but it provides a client with admin rights that can bypass "admin mode".
The client is initialized with the NHOST_ADMIN_SECRET you must have in your .env file. Checkout the doc if you want to know more about [admin secret](https://docs.nhost.io/reference/javascript/storage/set-admin-secret).
Define your server route and just import the serverNhostAdminSecret from @nhost/server. server/api/customers-sensitive.ts
import { serverNhostAdminSecret } from '@nhost/server'
export default defineEventHandler(async (event) => {
const client = await serverNhostAdminSecret(event)
const CUSTOMERS = gql`
query {
customers {
id
name
}
}
`
const { data, error } = await client.graphql.request(CUSTOMERS)
return { customers: data }
})
Then call your API route from any vue file:
const fetchSensitiveData = async () => {
const { customers } = await useFetch('/api/customers-sensitive')
}
serverNhostUser
This function is similar to the useNhostUser composable but is used in server routes. Define your server route and import the serverNhostUser from @nhost/server.
server/api/me.ts
import { serverNhostUser } from '@nhost/server'
export default defineEventHandler(async (event) => {
const user = await serverNhostUser(event)
return user
})
Then call your API route from any vue file:
const userFromServer = useState('userFromServer', () => '')
const fetchUserFromServerRoute = async () => {
userFromServer.value = await $fetch('/api/me')
}
Be careful, if you want to call this route on SSR, please read this section, you must send your browser cookies including your nhost token.
const userFromServer = useState('userFromServer', () => '')
const { data } = await useFetch('/api/me', {
headers: useRequestHeaders(['cookie'])
})
userFromServer.value = data