new docs
This commit is contained in:
5
.changeset/many-wolves-add.md
Normal file
5
.changeset/many-wolves-add.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@nhost/docs': major
|
||||
---
|
||||
|
||||
New Docs powered by Mintlify
|
||||
3
docs/.gitignore
vendored
3
docs/.gitignore
vendored
@@ -5,7 +5,6 @@
|
||||
/build
|
||||
|
||||
# Generated files
|
||||
.docusaurus
|
||||
.cache-loader
|
||||
|
||||
# Misc
|
||||
@@ -18,5 +17,3 @@
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.vercel
|
||||
docs/reference/docgen
|
||||
@@ -1,37 +1,32 @@
|
||||
# Nhost Docs
|
||||
# Mintlify Starter Kit
|
||||
|
||||
This documentation describes how to build, start and test the documentation locally.
|
||||
Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including
|
||||
|
||||
### Installation
|
||||
- Guide pages
|
||||
- Navigation
|
||||
- Customizations
|
||||
- API Reference pages
|
||||
- Use of popular components
|
||||
|
||||
```bash
|
||||
$ pnpm i
|
||||
### Development
|
||||
|
||||
Install the [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the documentation changes locally. To install, use the following command
|
||||
|
||||
```
|
||||
npm i -g mintlify
|
||||
```
|
||||
|
||||
### Local Development
|
||||
Run the following command at the root of your documentation (where mint.json is)
|
||||
|
||||
```bash
|
||||
$ pnpm start
|
||||
```
|
||||
mintlify dev
|
||||
```
|
||||
|
||||
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
|
||||
### Publishing Changes
|
||||
|
||||
### Build
|
||||
Install our Github App to autopropagate changes from youre repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard.
|
||||
|
||||
```bash
|
||||
$ pnpm build
|
||||
```
|
||||
#### Troubleshooting
|
||||
|
||||
This command generates static content into the `build` directory and can be served using any static contents hosting service.
|
||||
|
||||
### Serve
|
||||
|
||||
```bash
|
||||
$ pnpm serve
|
||||
```
|
||||
|
||||
This command serves the static content from the `build` directory.
|
||||
|
||||
### Contributing
|
||||
|
||||
All pull requests are greatly appreciated! See our [contributing guide](https://github.com/nhost/nhost/blob/main/CONTRIBUTING.md) to get started.
|
||||
- Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies.
|
||||
- Page loads as a 404 - Make sure you are running in a folder with `mint.json`
|
||||
|
||||
3
docs/_snippets/snippet-example.mdx
Normal file
3
docs/_snippets/snippet-example.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
## My Snippet
|
||||
|
||||
<Info>This is an example of a reusable snippet</Info>
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/mfa
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/email/change
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/deanonymize
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /healthz
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /version
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /token
|
||||
---
|
||||
3
docs/api-reference/auth/general/veify-jwt-token.mdx
Normal file
3
docs/api-reference/auth/general/veify-jwt-token.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /token/verify
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /verify
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /mfa/totp/generate
|
||||
---
|
||||
3
docs/api-reference/auth/get-user-information.mdx
Normal file
3
docs/api-reference/auth/get-user-information.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /user
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/webauthn/add
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: get /signin/provider/{provider}/callback
|
||||
sidebarTitle: Sign In Callback
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/provider/tokens
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/password/reset
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/email/send-verification-email
|
||||
---
|
||||
3
docs/api-reference/auth/set-a-new-password.mdx
Normal file
3
docs/api-reference/auth/set-a-new-password.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/password
|
||||
---
|
||||
3
docs/api-reference/auth/sign-in-anonymous.mdx
Normal file
3
docs/api-reference/auth/sign-in-anonymous.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /signin/anonymous
|
||||
---
|
||||
4
docs/api-reference/auth/sign-in-email-and-password.mdx
Normal file
4
docs/api-reference/auth/sign-in-email-and-password.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signin/email-password
|
||||
sidebarTitle: 'Sign In'
|
||||
---
|
||||
4
docs/api-reference/auth/sign-in-email-passwordless.mdx
Normal file
4
docs/api-reference/auth/sign-in-email-passwordless.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signin/passwordless/email
|
||||
sidebarTitle: Sign In Email
|
||||
---
|
||||
4
docs/api-reference/auth/sign-in-oauth-provider.mdx
Normal file
4
docs/api-reference/auth/sign-in-oauth-provider.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: get /signin/provider/{provider}
|
||||
sidebarTitle: Sign In
|
||||
---
|
||||
4
docs/api-reference/auth/sign-in-sms-passwordless-otp.mdx
Normal file
4
docs/api-reference/auth/sign-in-sms-passwordless-otp.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signin/passwordless/sms/otp
|
||||
sidebarTitle: Sign In SMS Verify OTP
|
||||
---
|
||||
4
docs/api-reference/auth/sign-in-sms-passwordless.mdx
Normal file
4
docs/api-reference/auth/sign-in-sms-passwordless.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signin/passwordless/sms
|
||||
sidebarTitle: Sign In SMS
|
||||
---
|
||||
3
docs/api-reference/auth/sign-in-totp.mdx
Normal file
3
docs/api-reference/auth/sign-in-totp.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /signin/mfa/totp
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signin/webauthn
|
||||
sidebarTitle: 'Sign In'
|
||||
---
|
||||
3
docs/api-reference/auth/sign-out.mdx
Normal file
3
docs/api-reference/auth/sign-out.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /signout
|
||||
---
|
||||
4
docs/api-reference/auth/sign-up-email-and-password.mdx
Normal file
4
docs/api-reference/auth/sign-up-email-and-password.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signup/email-password
|
||||
sidebarTitle: Sign Up
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signup/webauthn
|
||||
sidebarTitle: Sign Up
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /user/webauthn/verify
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signup/webauthn/verify
|
||||
sidebarTitle: Sign Up Verify
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
openapi: post /signin/webauthn/verify
|
||||
sidebarTitle: Sign In Verify
|
||||
---
|
||||
34
docs/api-reference/introduction.mdx
Normal file
34
docs/api-reference/introduction.mdx
Normal file
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: 'Introduction'
|
||||
description: ''
|
||||
---
|
||||
|
||||
## API Playground
|
||||
|
||||
The playground in next sections allow you learn and test the API against a real Nhost instance.
|
||||
|
||||
|
||||
To learn how to start a local Nhost instance head to [local development](/local-development)
|
||||
|
||||
```bash
|
||||
> nhost up
|
||||
|
||||
Nhost development environment started.
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5432/local
|
||||
- Hasura: https://local.hasura.nhost.run
|
||||
- GraphQL: https://local.graphql.nhost.run
|
||||
- Auth: https://local.auth.nhost.run
|
||||
- Storage: https://local.storage.nhost.run
|
||||
- Functions: https://local.functions.nhost.run
|
||||
- Dashboard: https://local.dashboard.nhost.run
|
||||
- Mailhog: https://local.mailhog.nhost.run
|
||||
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
```
|
||||
2329
docs/api-reference/openapi-auth.yaml
Normal file
2329
docs/api-reference/openapi-auth.yaml
Normal file
File diff suppressed because it is too large
Load Diff
899
docs/api-reference/openapi-storage.yaml
Normal file
899
docs/api-reference/openapi-storage.yaml
Normal file
@@ -0,0 +1,899 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/schemas/v3.0/schema.yaml
|
||||
---
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
description: Hasura Storage
|
||||
version: 1.0.0
|
||||
title: Hasura Storage
|
||||
license:
|
||||
name: LICENSE-TBD
|
||||
url: https://LICENSE-TBD
|
||||
servers:
|
||||
- url: https://local.storage.nhost.run/v1
|
||||
description: API Server
|
||||
security:
|
||||
- AdminSecret: []
|
||||
- Authorization: []
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
AdminSecret:
|
||||
type: apiKey
|
||||
in: header
|
||||
name: X-Hasura-Admin-Secret
|
||||
description: Hasura Admin Secret
|
||||
Authorization:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
description: JSON Web Token to authorize requests.
|
||||
schemas:
|
||||
VersionInformation:
|
||||
type: object
|
||||
properties:
|
||||
buildVersion:
|
||||
type: string
|
||||
FileSummary:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
bucketId:
|
||||
type: string
|
||||
isUploaded:
|
||||
type: boolean
|
||||
FileMetadata:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
size:
|
||||
type: number
|
||||
bucketId:
|
||||
type: string
|
||||
eTag:
|
||||
type: string
|
||||
createdAt:
|
||||
type: string
|
||||
format: date-time
|
||||
updatedAt:
|
||||
type: string
|
||||
format: date-time
|
||||
isUploaded:
|
||||
type: boolean
|
||||
mimeType:
|
||||
type: string
|
||||
uploadedByUserId:
|
||||
type: string
|
||||
metadata:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
UploadFileMetadata:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
metadata:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
UpdateFileMetadata:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
metadata:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
PresignedURLResponse:
|
||||
type: object
|
||||
properties:
|
||||
url:
|
||||
type: string
|
||||
expiration:
|
||||
type: number
|
||||
Error:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: object
|
||||
properties:
|
||||
message:
|
||||
type: string
|
||||
|
||||
paths:
|
||||
/openapi.yaml:
|
||||
get:
|
||||
summary: Return this schema definition
|
||||
tags:
|
||||
- documentation
|
||||
responses:
|
||||
'200':
|
||||
description: Return this schema definition
|
||||
content:
|
||||
application/x-yaml:
|
||||
schema:
|
||||
type: object
|
||||
/version:
|
||||
get:
|
||||
summary: Retrieve build information about the server
|
||||
tags:
|
||||
- documentation
|
||||
responses:
|
||||
'200':
|
||||
description: Return build information
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/VersionInformation'
|
||||
|
||||
/files/:
|
||||
post:
|
||||
summary: Upload File
|
||||
description: Upload one or multiple files at once
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
- AdminSecret: []
|
||||
requestBody:
|
||||
content:
|
||||
multipart/form-data:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
bucket-id:
|
||||
type: string
|
||||
description: Bucket to upload the files to
|
||||
metadata[]:
|
||||
type: array
|
||||
description: (Optional) Set the following metadata for the uploaded files instead of letting the server do it automatically. See "UploadFileMetadata".
|
||||
items:
|
||||
$ref: '#/components/schemas/UploadFileMetadata'
|
||||
file[]:
|
||||
description: Array of files to upload.
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
format: binary
|
||||
encoding:
|
||||
file[]:
|
||||
contentType: application/octet-stream
|
||||
responses:
|
||||
'201':
|
||||
description: File was uploaded successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ProcessedFiles:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/FileMetadata'
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
/files/{id}:
|
||||
head:
|
||||
summary: "Download File Metadata"
|
||||
description: "Retrieve metadata of a file"
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
parameters:
|
||||
- name: id
|
||||
required: true
|
||||
in: path
|
||||
schema:
|
||||
type: string
|
||||
- name: if-match
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-none-match
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-modified-since
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-unmodified-since
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Unmodified-Since
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: q
|
||||
description: Quality of the image. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: h
|
||||
description: Resize image up to h maintaining aspect ratio. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: w
|
||||
description: Resize image up to w maintaining aspect ratio. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: b
|
||||
description: Blur the image according to this sigma value. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
responses:
|
||||
'200':
|
||||
description: File information gathered successfully
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
'304':
|
||||
description: |
|
||||
File hasn't been modified based on:
|
||||
- file modification time is older than If-Modified-Since
|
||||
- etag matches one of If-None-Match
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
'412':
|
||||
description: |
|
||||
Some of the conditions specified in the headers failed to match. For instance:
|
||||
- etag doesn't match one of If-Match
|
||||
- if-unmodified-since is false
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
default:
|
||||
description: Some error occurred
|
||||
headers:
|
||||
X-Error:
|
||||
description: An error message
|
||||
schema:
|
||||
type: string
|
||||
get:
|
||||
summary: Download File
|
||||
description: "Download a file from storage"
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
parameters:
|
||||
- name: id
|
||||
required: true
|
||||
in: path
|
||||
schema:
|
||||
type: string
|
||||
- name: if-match
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-none-match
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-modified-since
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-unmodified-since
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Unmodified-Since
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: q
|
||||
description: Quality of the image. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: h
|
||||
description: Resize image up to h maintaining aspect ratio. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: w
|
||||
description: Resize image up to w maintaining aspect ratio. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: b
|
||||
description: Blur the image according to this sigma value. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
responses:
|
||||
'200':
|
||||
description: File gathered successfully
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
content:
|
||||
application/octet-stream: {}
|
||||
'304':
|
||||
description: |
|
||||
File hasn't been modified based on:
|
||||
- file modification time is older than If-Modified-Since
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
'412':
|
||||
description: |
|
||||
Some of the conditions specified in the headers failed to match. For instance:
|
||||
- etag doesn't match one of If-Match
|
||||
- etag matches one of If-None-Match
|
||||
- if-unmodified-since is false
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
default:
|
||||
description: Some error occurred
|
||||
headers:
|
||||
X-Error:
|
||||
description: An error message
|
||||
schema:
|
||||
type: string
|
||||
put:
|
||||
summary: Replace File
|
||||
description: Replace the contents of an existing file
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
parameters:
|
||||
- name: id
|
||||
required: true
|
||||
in: path
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
multipart/form-data:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
metadata:
|
||||
$ref: '#/components/schemas/UpdateFileMetadata'
|
||||
file:
|
||||
description: New contents of the file to upload.
|
||||
encoding:
|
||||
file:
|
||||
contentType: application/octet-stream
|
||||
responses:
|
||||
'200':
|
||||
description: File was uploaded successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/FileMetadata'
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
delete:
|
||||
summary: Delete File
|
||||
description: "Delete file from storage"
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
parameters:
|
||||
- name: id
|
||||
required: true
|
||||
in: path
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
'204':
|
||||
description: File was deleted successfully
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
/files/{id}/presignedurl:
|
||||
get:
|
||||
summary: Presigned URL
|
||||
description: |
|
||||
Retrieve presigned URL to retrieve the file. Expiration of the URL is
|
||||
determined by bucket configuration
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
parameters:
|
||||
- name: id
|
||||
required: true
|
||||
in: path
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: File gathered successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PresignedURLResponse'
|
||||
|
||||
default:
|
||||
description: Some error occurred
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
/files/{id}/presignedurl/contents:
|
||||
get:
|
||||
summary: "Get File Content"
|
||||
description: "Retrieve content of a file"
|
||||
tags:
|
||||
- storage
|
||||
security:
|
||||
- Authorization: []
|
||||
parameters:
|
||||
- name: id
|
||||
required: true
|
||||
in: path
|
||||
schema:
|
||||
type: string
|
||||
- name: X-Amz-Algorithm
|
||||
description: Use presignedurl endpoint to generate this automatically
|
||||
required: true
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: X-Amz-Credential
|
||||
description: Use presignedurl endpoint to generate this automatically
|
||||
required: true
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: X-Amz-Date
|
||||
description: Use presignedurl endpoint to generate this automatically
|
||||
required: true
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: X-Amz-Expires
|
||||
description: Use presignedurl endpoint to generate this automatically
|
||||
required: true
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: X-Amz-Signature
|
||||
description: Use presignedurl endpoint to generate this automatically
|
||||
required: true
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: X-Amz-SignedHeaders
|
||||
description: Use presignedurl endpoint to generate this automatically
|
||||
required: true
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: if-match
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-none-match
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-modified-since
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: if-unmodified-since
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Unmodified-Since
|
||||
in: header
|
||||
schema:
|
||||
type: string
|
||||
- name: q
|
||||
description: Quality of the image. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: h
|
||||
description: Resize image up to h maintaining aspect ratio. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: w
|
||||
description: Resize image up to w maintaining aspect ratio. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
- name: b
|
||||
description: Blur the image according to this sigma value. Only applies to jpeg, webp and png files
|
||||
in: query
|
||||
schema:
|
||||
type: number
|
||||
responses:
|
||||
'200':
|
||||
description: File gathered successfully
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
Accept-Ranges:
|
||||
description: Always set to bytes. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges
|
||||
schema:
|
||||
type: string
|
||||
content:
|
||||
application/octet-stream: {}
|
||||
'206':
|
||||
description: File partially gathered successfully
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
Accept-Ranges:
|
||||
description: Always set to bytes. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges
|
||||
schema:
|
||||
type: string
|
||||
Content-Range:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
|
||||
schema:
|
||||
type: string
|
||||
content:
|
||||
application/octet-stream: {}
|
||||
'304':
|
||||
description: |
|
||||
File hasn't been modified based on:
|
||||
- file modification time is older than If-Modified-Since
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
'412':
|
||||
description: |
|
||||
Some of the conditions specified in the headers failed to match. For instance:
|
||||
- etag doesn't match one of If-Match
|
||||
- etag matches one of If-None-Match
|
||||
- if-unmodified-since is false
|
||||
headers:
|
||||
Cache-Control:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
||||
schema:
|
||||
type: string
|
||||
Content-Length:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length
|
||||
schema:
|
||||
type: number
|
||||
Content-Type:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
|
||||
schema:
|
||||
type: string
|
||||
Etag:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Etag
|
||||
schema:
|
||||
type: string
|
||||
Last-Modified:
|
||||
description: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
|
||||
schema:
|
||||
type: string
|
||||
default:
|
||||
description: Some error occurred
|
||||
headers:
|
||||
X-Error:
|
||||
description: An error message
|
||||
schema:
|
||||
type: string
|
||||
|
||||
/ops/list-orphans:
|
||||
post:
|
||||
summary: Lists orphaned files
|
||||
description: Orphaned files are files that are present in the storage but have no associated metadata
|
||||
tags:
|
||||
- operations
|
||||
security:
|
||||
- X-Hasura-Admin-Secret: []
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully computed orphaned files
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
files:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
/ops/delete-orphans:
|
||||
post:
|
||||
summary: Deletes orphaned files
|
||||
description: Orphaned files are files that are present in the storage but have no associated metadata
|
||||
tags:
|
||||
- operations
|
||||
security:
|
||||
- X-Hasura-Admin-Secret: []
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully deleted orphaned files
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
files:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
/ops/list-broken-metadata:
|
||||
post:
|
||||
summary: Lists broken metadata
|
||||
description: Broken metadata is defined as metadata that has isUploaded = true but there is no file in the storage matching it
|
||||
tags:
|
||||
- operations
|
||||
security:
|
||||
- X-Hasura-Admin-Secret: []
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully computed broken metadata
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
metadata:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/FileSummary'
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
/ops/delete-broken-metadata:
|
||||
post:
|
||||
summary: Delete broken metadata
|
||||
description: Broken metadata is defined as metadata that has isUploaded = true but there is no file in the storage matching it
|
||||
tags:
|
||||
- operations
|
||||
security:
|
||||
- X-Hasura-Admin-Secret: []
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully deleted broken metadata
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
metadata:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/FileSummary'
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
/ops/list-not-uploaded:
|
||||
post:
|
||||
summary: Lists files that haven't been uploaded
|
||||
description: That is, metadata that has isUploaded = false
|
||||
tags:
|
||||
- operations
|
||||
security:
|
||||
- X-Hasura-Admin-Secret: []
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully checked files not uploaded
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
metadata:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/FileSummary'
|
||||
default:
|
||||
description: En error occured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /version
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /openapi.yaml
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /ops/delete-broken-metadata
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /ops/delete-orphans
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /ops/list-broken-metadata
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /ops/list-not-uploaded
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /ops/list-orphans
|
||||
---
|
||||
3
docs/api-reference/storage/storage/delete-a-file.mdx
Normal file
3
docs/api-reference/storage/storage/delete-a-file.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: delete /files/{id}
|
||||
---
|
||||
3
docs/api-reference/storage/storage/replace-file.mdx
Normal file
3
docs/api-reference/storage/storage/replace-file.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: put /files/{id}
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /files/{id}/presignedurl/contents
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /files/{id}
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: head /files/{id}
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: get /files/{id}/presignedurl
|
||||
---
|
||||
3
docs/api-reference/storage/storage/upload-files.mdx
Normal file
3
docs/api-reference/storage/storage/upload-files.mdx
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
openapi: post /files/
|
||||
---
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
|
||||
};
|
||||
161
docs/development/cli/commands.mdx
Normal file
161
docs/development/cli/commands.mdx
Normal file
@@ -0,0 +1,161 @@
|
||||
---
|
||||
title: Commands
|
||||
description: Available commands to run and manage local Nhost projects
|
||||
---
|
||||
|
||||
## `nhost init`
|
||||
|
||||
Initializes current directory with a new project containing configuration and objects necessary to run Nhost locally.
|
||||
|
||||
<Accordion title="Output">
|
||||
|
||||
Initializing Nhost project
|
||||
|
||||
Successfully initialized Nhost project, run `nhost up` to start development
|
||||
</Accordion>
|
||||
|
||||
### Flags
|
||||
|
||||
`--remote` optional `false` <br />
|
||||
Pulls state from a remote Nhost instance.
|
||||
|
||||
|
||||
## `nhost up`
|
||||
|
||||
Starts Nhost for development and testing purposes. Requires scaffolding from `nhost init`.
|
||||
|
||||
<Accordion title="Output">
|
||||
|
||||
```
|
||||
Nhost development environment started.
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5432/local
|
||||
- Hasura: https://local.hasura.nhost.run
|
||||
- GraphQL: https://local.graphql.nhost.run
|
||||
- Auth: https://local.auth.nhost.run
|
||||
- Storage: https://local.storage.nhost.run
|
||||
- Functions: https://local.functions.nhost.run
|
||||
- Dashboard: https://local.dashboard.nhost.run
|
||||
- Mailhog: https://local.mailhog.nhost.run
|
||||
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
|
||||
|
||||
|
||||
## `nhost down`
|
||||
|
||||
Stops all services and deletes all containers.
|
||||
|
||||
### Flags
|
||||
|
||||
`--volumes` optional `false` <br />
|
||||
Remove volumes.
|
||||
|
||||
|
||||
## `nhost login`
|
||||
|
||||
Login to an Nhost account to perform authenticated operations.
|
||||
|
||||
<Accordion title="Output">
|
||||
- email: user@domain.com
|
||||
- password:
|
||||
|
||||
Authenticating <br />
|
||||
Successfully logged in, creating PAT <br />
|
||||
Successfully created PAT <br />
|
||||
Storing PAT for future user
|
||||
|
||||
</Accordion>
|
||||
|
||||
### Flags
|
||||
|
||||
`--email` optional <br />
|
||||
Email adress.
|
||||
|
||||
`--password` optional <br />
|
||||
Password.
|
||||
|
||||
`--pat` optional <br />
|
||||
Use this Personal Access Token instead of generating a new one with email/password.
|
||||
|
||||
## `nhost logs`
|
||||
|
||||
Render all logs.
|
||||
|
||||
<Accordion title="Output">
|
||||
```
|
||||
app-auth-1 | {"level":"info","message":"Applying SQL migrations..."}
|
||||
app-auth-1 | {"level":"info","message":"SQL migrations applied"}
|
||||
app-auth-1 | {"level":"info","message":"Applying metadata..."}
|
||||
app-auth-1 | {"level":"info","message":"Metadata applied"}
|
||||
app-auth-1 | {"level":"info","message":"Running on port 4000"}
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
### Flags
|
||||
|
||||
`--follow` optional <br />
|
||||
Follow (or tail) log output.
|
||||
|
||||
`--no-color` optional <br />
|
||||
Produce monochrome output.
|
||||
|
||||
`--no-log-prefix` optional <br />
|
||||
Don't print prefix in logs.
|
||||
|
||||
`--since` optional <br />
|
||||
Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
|
||||
|
||||
`--tail` optional `all`<br />
|
||||
Number of lines to show from the end of the logs for each service
|
||||
|
||||
`--timestamps` optional <br />
|
||||
Show timestamps
|
||||
|
||||
`--until` optional <br />
|
||||
Show logs before a timestamp
|
||||
|
||||
## `nhost list`
|
||||
|
||||
List all remote Nhost projects this user has access to.
|
||||
|
||||
<Accordion title="Output">
|
||||
|
||||
```
|
||||
# │ Subdomain │ Project │ Workspace │ Region │
|
||||
1 │ dahvgwlspuridghplrso │ nbp │ Nuno's Workspace │ eu-central-1 │
|
||||
2 │ mhmvhergiiycqfvhisan │ Bun Generator │ Nhost Examples │ eu-central-1 │
|
||||
4 │ qaxzubvwbuhzgxswghug │ Next.js Stripe Starter Template │ Nhost Examples │ eu-central-1 │
|
||||
5 │ cuzwcdqwgmhbxqetfbci │ Nhost Netlify Starter Template │ Nhost Examples │ us-east-1 │
|
||||
6 │ jsjiiuwiuqdvvwgwhxnx │ quickstarts │ Nhost Examples │ eu-central-1 │
|
||||
7 │ vvhjnsgebtspueuuxnvp │ React Apollo │ Nhost Examples │ eu-central-1 │
|
||||
9 │ vue-quickstart │ vue-quickstart │ Nhost Examples │ eu-central-1 │
|
||||
11 │ odqlmnqxospbvqvphuyl │ monitoring-app-frankfurt │ monitoring │ eu-central-1 │
|
||||
12 │ xmhqdbhkvskuubnelgkc │ monitoring-app-london │ monitoring │ eu-west-2 │
|
||||
13 │ jjetetkbmovfgyewremk │ monitoring-app-mumbai │ monitoring │ ap-south-1 │
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
## `nhost secrets`
|
||||
|
||||
Manage secrets in the Nhost cloud.
|
||||
|
||||
### `nhost secrets create`
|
||||
|
||||
#### Flags
|
||||
|
||||
<Accordion title="Output">
|
||||
|
||||
</Accordion>
|
||||
|
||||
86
docs/development/cli/getting-started.mdx
Normal file
86
docs/development/cli/getting-started.mdx
Normal file
@@ -0,0 +1,86 @@
|
||||
---
|
||||
title: Nhost CLI
|
||||
description: Tools to develop and test Nhost projects locally
|
||||
---
|
||||
|
||||
## Instaling the Nhost CLI
|
||||
|
||||
To install the Nhost CLI copy the following command and paste it into your terminal:
|
||||
|
||||
```bash
|
||||
> sudo curl -L https://raw.githubusercontent.com/nhost/cli/main/get.sh | bash
|
||||
```
|
||||
|
||||
The `get.sh` script checks for both the architecture and operating system and installs the right binary.
|
||||
|
||||
### Supported Platforms:
|
||||
|
||||
- MacOS
|
||||
- Linux
|
||||
- Windows WSL2
|
||||
|
||||
### Dependencies:
|
||||
|
||||
- [Docker](https://docs.docker.com/get-docker/)
|
||||
- [curl](https://curl.se/)
|
||||
- [Git](https://git-scm.com/downloads)
|
||||
|
||||
## Updating the Nhost CLI
|
||||
|
||||
Update an existing installation to the latest version.
|
||||
|
||||
```bash Terminal
|
||||
> nhost sw upgrade
|
||||
```
|
||||
|
||||
## Running Nhost
|
||||
|
||||
Inside of the folder where you want to create your project, run:
|
||||
|
||||
```bash Terminal
|
||||
> nhost init
|
||||
|
||||
Initializing Nhost project
|
||||
Successfully initialized Nhost project, run `nhost up` to start development
|
||||
```
|
||||
|
||||
`init` will scaffold a bunch of files that Nhost uses to manage configuration, database schema and migrations, APIs, functions, etc.
|
||||
|
||||
Now, to start the local Nhost instance, run:
|
||||
|
||||
```bash Terminal
|
||||
> nhost up
|
||||
|
||||
|
||||
Nhost development environment started.
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5432/local
|
||||
- Hasura: https://local.hasura.nhost.run
|
||||
- GraphQL: https://local.graphql.nhost.run
|
||||
- Auth: https://local.auth.nhost.run
|
||||
- Storage: https://local.storage.nhost.run
|
||||
- Functions: https://local.functions.nhost.run
|
||||
- Dashboard: https://local.dashboard.nhost.run
|
||||
- Mailhog: https://local.mailhog.nhost.run
|
||||
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
```
|
||||
|
||||
The following services are available:
|
||||
|
||||
- Postgres
|
||||
- Hasura Console
|
||||
- GraphQL API
|
||||
- Authentication
|
||||
- Storage
|
||||
- Functions
|
||||
- Dashboard
|
||||
- Mailhog (SMTP server for testing emails locally)
|
||||
|
||||
<Info>Support for Nhost Run services is coming soon</Info>
|
||||
20
docs/development/cli/overview.mdx
Normal file
20
docs/development/cli/overview.mdx
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: 'Overview'
|
||||
description: 'Developing locally with the Nhost CLI'
|
||||
---
|
||||
|
||||
Run the Nhost Stack on your computer with `nhost init` and `nhost start`. The Nhost CLI ships with all the tools you need to run, test, and operate your projects.
|
||||
|
||||
Manage configuration, database migrations, API schema changes, and more, with ease.
|
||||
|
||||
|
||||
|
||||
### Resources
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Nhost CLI" icon="square-1">
|
||||
</Card>
|
||||
<Card title="Nhost Deployments" icon="square-2">
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
4
docs/development/cli/recommended-workflow.mdx
Normal file
4
docs/development/cli/recommended-workflow.mdx
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: Recommended Workflow
|
||||
description: the recommended workflow
|
||||
---
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "Authentication",
|
||||
"position": 6
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
---
|
||||
title: Email Templates
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
Nhost Auth sends out transactional emails as part of the authentication service. These emails can be modified using email templates.
|
||||
|
||||
The following email templates are available:
|
||||
|
||||
- **email-verify** - Verify email address
|
||||
- **email-confirm-change** - Confirm email change to a new email address.
|
||||
- **signin-passwordless** - Magic Link
|
||||
- **password-reset** - Reset password
|
||||
|
||||
Changing email templates is only available for projects on the [Pro and Enterprise plan](https://nhost.io/pricing).
|
||||
|
||||
## Update Email Templates
|
||||
|
||||
Your project must be connected to a [Git Repository](/platform/git) to be able to change the email templates.
|
||||
|
||||
Email templates are automatically deployed during a deployment, just like database migrations, Hasura metadata, and Serverless Functions.
|
||||
|
||||
## File Structure
|
||||
|
||||
Emails are located in the `nhost/` folder like this:
|
||||
|
||||
The email templates should be provided as body.html and subject.txt files in this predefined folder structure.
|
||||
|
||||
**Example:** Email templates for `en` (English) and `es` (Spanish):
|
||||
|
||||
```txt
|
||||
my-nhost-project/
|
||||
└── nhost/
|
||||
├── config.yaml
|
||||
├── emails/
|
||||
│ ├── en/
|
||||
│ │ ├── email-verify/
|
||||
│ │ │ ├── subject.txt
|
||||
│ │ │ └── body.html
|
||||
│ │ ├── email-confirm-change/
|
||||
│ │ │ ├── subject.txt
|
||||
│ │ │ └── body.html
|
||||
│ │ ├── signin-passwordless/
|
||||
│ │ │ ├── subject.txt
|
||||
│ │ │ └── body.html
|
||||
│ │ └── password-reset/
|
||||
│ │ ├── subject.txt
|
||||
│ │ └── body.html
|
||||
│ └── es/
|
||||
│ ├── email-verify/
|
||||
│ │ ├── subject.txt
|
||||
│ │ └── body.html
|
||||
│ ├── email-confirm-change/
|
||||
│ │ ├── subject.txt
|
||||
│ │ └── body.html
|
||||
│ ├── signin-passwordless/
|
||||
│ │ ├── subject.txt
|
||||
│ │ └── body.html
|
||||
│ └── password-reset/
|
||||
│ ├── subject.txt
|
||||
│ └── body.html
|
||||
├── migrations/
|
||||
├── metadata/
|
||||
└── seeds
|
||||
```
|
||||
|
||||
As you see, the format is:
|
||||
|
||||
```
|
||||
nhost/emails/{two-letter-language-code}/{email-template}/[subject.txt, body.html]
|
||||
```
|
||||
|
||||
## Languages
|
||||
|
||||
The user's language is what decides what template to send. The user's language is stored in the `auth.users` table in the `locale` column. This `locale` column contains a two-letter language code in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format.
|
||||
|
||||
This value is `en` by default for new users.
|
||||
|
||||
## Variables
|
||||
|
||||
The following variables are available to use in the email templates:
|
||||
|
||||
| Variable | Description |
|
||||
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| link | The full URL to the target of the transaction. This should be used in the main call to action. This is available in all templates. |
|
||||
| serverUrl | URL of the authentication server |
|
||||
| clientUrl | URL to your frontend app |
|
||||
| redirectTo | URL where the user will be redirected to after clicking the link and finishing the action of the email |
|
||||
| ticket | Ticket that is used to authorize the link request |
|
||||
| displayName | The display name of the user. |
|
||||
| email | The email of the user. |
|
||||
| locale | Locale of the user as a two-letter language code. E.g. "en". |
|
||||
|
||||
Use variables like this: `${displayName}` in the email templates.
|
||||
|
||||
**Example:** A email template to verify users' emails:
|
||||
|
||||
```html title="nhost/emails/en/email-verify/body.html"
|
||||
<h2>Verify You Email</h2>
|
||||
|
||||
<p>Hi, ${displayName}! Please click the link to verify your email:</p>
|
||||
|
||||
<p>
|
||||
<a href="${link}">Verify Email</a>
|
||||
</p>
|
||||
```
|
||||
@@ -1,86 +0,0 @@
|
||||
---
|
||||
title: Authentication
|
||||
sidebar_label: Overview
|
||||
sidebar_position: 1
|
||||
image: /img/og/authentication.png
|
||||
---
|
||||
|
||||
Nhost Authentication is a ready-to-use authentication service that is integrated with the [GraphQL API](/graphql) and its permission system from Hasura. This allows you to easily add user authentication to your application without having to build and maintain your own authentication system.
|
||||
|
||||
Nhost Authentication lets you authenticate users using different sign-in methods:
|
||||
|
||||
- [Email and Password](/authentication/sign-in-with-email-and-password)
|
||||
- [Magic Link](/authentication/sign-in-with-magic-link)
|
||||
- [Phone Number (SMS)](/authentication/sign-in-with-phone-number-sms)
|
||||
- [Security Keys (WebAuthn)](/authentication/sign-in-with-security-keys)
|
||||
- [Apple](/authentication/sign-in-with-apple)
|
||||
- [Discord](/authentication/sign-in-with-discord)
|
||||
- [Facebook](/authentication/sign-in-with-facebook)
|
||||
- [GitHub](/authentication/sign-in-with-github)
|
||||
- [Google](/authentication/sign-in-with-google)
|
||||
- [LinkedIn](/authentication/sign-in-with-linkedin)
|
||||
- [Spotify](/authentication/sign-in-with-spotify)
|
||||
- [Twitch](/authentication/sign-in-with-twitch)
|
||||
- [WorkOS](/authentication/sign-in-with-workos)
|
||||
|
||||
## Client URL
|
||||
|
||||
Client URL is the URL of your frontend application. The Client URL is used to redirect the user after interacting with any authentication operation, like signing in or resetting their password.
|
||||
|
||||
## Allowed Redirect URLs
|
||||
|
||||
Allowed Redirect URLs are the URLs of your frontend application that are allowed to redirect the user after interacting with any authentication operation, like signing in or resetting their password. This is useful if you have multiple frontend applications that are using the same Nhost backend or if you want to redirect the user to a specific URL after interacting with an authentication operation.
|
||||
|
||||
As an example, for a staging project, you can set the Client URL to `https://staging.example.com` and Allowed Redirect URLs to `https://*.vercel.app`. This way, the user can be redirected to any Vercel deployment of your frontend application.
|
||||
|
||||
## Allowed Emails and Domains
|
||||
|
||||
Allowed Emails and Domains are used to restrict the sign-up an sign-in process to specific email addresses and domains.
|
||||
|
||||
If both allowed emails and allowed domains are set a user can only sign up if their email address matches one of the allowed emails or one of the allowed domains.
|
||||
|
||||
## Blocked Emails and Domains
|
||||
|
||||
Blocked Emails and Domains are used to block specific email addresses and domains from signing up and singin in.
|
||||
|
||||
Note that even if a user's email address matches any allowed email or domain, they will still be blocked if their email address matches any blocked email or domain.
|
||||
|
||||
## Multi-factor Authentication
|
||||
|
||||
By enabling Multi-factor Authentication (MFA), you can allow users to verify their identity using a second factor during the sign-in process. We currently support Authenticator Apps (TOTP) for MFA.
|
||||
|
||||
Once MFA is enabled, a user can enable MFA for their account by scanning a QR code with their Authenticator App. After that, they will be prompted to enter a code generated by their Authenticator App during the sign-in process.
|
||||
|
||||
We'll be adding more support in our SDKs and documentation around MFA soon.
|
||||
|
||||
## Gravatar
|
||||
|
||||
If Gravatar is enabled, Nhost Auth will use the user's email address to fetch their Gravatar profile picture. If the user doesn't have a Gravatar profile picture, a default image will be used.
|
||||
|
||||
There are two options for Gravatars:
|
||||
|
||||
### Default Image
|
||||
|
||||
If the user doesn't have a Gravatar profile picture, a default image will be used. You can choose between the following options:
|
||||
|
||||
- `404`: Do not load any image if none is associated with the email hash, instead return an HTTP 404 (File Not Found) response.
|
||||
- `mp`: (mystery-person) a simple, cartoon-style silhouetted outline of a person (does not vary by email hash).
|
||||
- `identicon`: a geometric pattern based on an email hash.
|
||||
- `monsterid`: a generated 'monster' with different colors, faces, etc.
|
||||
- `wavatar`: generated faces with differing features and backgrounds.
|
||||
- `retro`: awesome generated, 8-bit arcade-style pixelated faces.
|
||||
- `robohash`: a generated robot with different colors, faces, etc.
|
||||
- `blank`: a transparent PNG image.
|
||||
|
||||
### Rating
|
||||
|
||||
Gravatar images are rated by default. You can choose between the following options:
|
||||
|
||||
- `g`: suitable for display on all websites with any audience type.
|
||||
- `pg`: may contain rude gestures, provocatively dressed individuals, lesser swear words or mild violence.
|
||||
- `r`: may contain such things as harsh profanity, intense violence, nudity, or hard drug use.
|
||||
- `x`: may contain hardcore sexual imagery or extremely disturbing violence.
|
||||
|
||||
## Disable New Users
|
||||
|
||||
If set, newly registered users are disabled and won't be able to sign in. This is useful if you want to manually approve new users before they can sign in.
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
title: Sign In with Email and Password
|
||||
sidebar_label: Email and Password
|
||||
slug: /authentication/sign-in-with-email-and-password
|
||||
image: /img/og/sign-in-with-email-and-password.png
|
||||
---
|
||||
|
||||
The Email and Password sign-in method is always enabled for all Nhost projects.
|
||||
|
||||
## Sign Up
|
||||
|
||||
Users must first sign up to be able to sign in.
|
||||
|
||||
**Example:** Sign up users using the [Nhost JavaScript client](/reference/javascript).
|
||||
|
||||
```js
|
||||
await nhost.auth.signUp({
|
||||
email: 'joe@example.com',
|
||||
password: 'secret-password'
|
||||
})
|
||||
```
|
||||
|
||||
If you've turned on email verification in your project's **Authentication Settings**, a user will be sent a verification email upon signup. The user must click the verification link in the email before they can sign in.
|
||||
|
||||
## Sign In
|
||||
|
||||
After the user has successfully signed up, they can sign in.
|
||||
|
||||
**Example:** Sign in users using the [Nhost JavaScript client](/reference/javascript).
|
||||
|
||||
```js
|
||||
await nhost.auth.signIn({
|
||||
email: 'joe@example.com',
|
||||
password: 'secret-password'
|
||||
})
|
||||
```
|
||||
|
||||
## Email Verification
|
||||
|
||||
If you want to require users to verify their email before they can sign in, you can enable this under **Settings -> Sign-In Methods -> Email and Password** by checking the **Require Verified Emails** checkbox.
|
||||
|
||||
If **Require Verified Emails** is enabled, users automatically get a verification email when they sign up. The user must click the verification link in the email before they can sign in. It's possible to edit the ["email-verify" email template](/authentication/email-templates).
|
||||
|
||||
It's possible to manually send a verification email to the user using [`nhost.auth.sendVerificationEmail()`](/reference/javascript/auth/send-verification-email).
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
title: Sign In with Magic Link
|
||||
sidebar_label: Magic Link
|
||||
slug: /authentication/sign-in-with-magic-link
|
||||
image: /img/og/sign-in-with-magic-link.png
|
||||
---
|
||||
|
||||
Nhost allows you to sign in users with a Magic Link, which is a way to sign in users so they don't have to remember a password.
|
||||
|
||||
When users sign in using this sign-in method, they'll enter their email address and then receive an email with a (magic) link. When the user clicks on the (magic) link, they get automatically signed in to your app.
|
||||
|
||||
The sign-in method is called Magic Link because the user gets "magically" signed in without having to enter a password.
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable the Magic Link sign-in method in the Nhost dashboard under **Settings -> Sign-In Methods -> Magic Link**.
|
||||
|
||||
## Sign In
|
||||
|
||||
To sign in users with Magic Link is a two-step process:
|
||||
|
||||
1. Send a Magic Link to the user's email address.
|
||||
2. The user clicks the Magic Link in their email to sign in.
|
||||
|
||||
Use the [Nhost JavaScript client](/reference/javascript) to sign in users with Magic Link:
|
||||
|
||||
```js
|
||||
nhost.auth.signIn({
|
||||
email: 'joe@example.com'
|
||||
})
|
||||
```
|
||||
|
||||
There is no sign up method for Magic Link. Users will be automatically created when they sign in for the first time.
|
||||
|
||||
Users who have signed up with email and password can also sign in with Magic Link.
|
||||
|
||||
## Email
|
||||
|
||||
It's possible to edit the ["signin-passwordless" email template](/authentication/email-templates).
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
title: Sign In with Personal Access Tokens
|
||||
sidebar_label: Personal Access Tokens
|
||||
slug: /authentication/sign-in-with-personal-access-tokens
|
||||
---
|
||||
|
||||
Nhost allows you to sign in users with personal access tokens (PAT) which is a way to sign in users without an email address or password.
|
||||
|
||||
## Configuration
|
||||
|
||||
:::info
|
||||
Personal Access Tokens can only be created through Hasura Auth or the [Nhost JavaScript SDK](/reference/javascript) at the moment.
|
||||
:::
|
||||
|
||||
## Create a Personal Access Token
|
||||
|
||||
Users must be signed in to create a personal access token. Once a user is signed in, they can create a personal access token.
|
||||
|
||||
**Example:** Create a personal access token:
|
||||
|
||||
```tsx
|
||||
const expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30) // 30 days
|
||||
const metadata = { name: 'Example PAT' } // Optional metadata
|
||||
|
||||
const { data, error } = await nhost.auth.createPAT(expiresAt, metadata)
|
||||
|
||||
// Something unexpected happened
|
||||
if (error) {
|
||||
console.error(error)
|
||||
return
|
||||
}
|
||||
|
||||
console.log(data.id) // The personal access token ID (can be used to delete the token later)
|
||||
console.log(data.personalAccessToken) // The personal access token
|
||||
```
|
||||
|
||||
Users can create multiple personal access tokens. Each token can have a different expiration date and metadata.
|
||||
|
||||
## Sign In
|
||||
|
||||
Once a user has created a personal access token, they can use it to sign in.
|
||||
|
||||
**Example:** Sign in with a personal access token:
|
||||
|
||||
```tsx
|
||||
const { error, session } = await nhost.auth.signInPAT('<personal-access-token>')
|
||||
|
||||
// Something unexpected happened
|
||||
if (error) {
|
||||
console.log(error)
|
||||
return
|
||||
}
|
||||
|
||||
// User is signed in
|
||||
console.log(session.user)
|
||||
```
|
||||
|
||||
## List or Remove Personal Access Tokens
|
||||
|
||||
To list and remove personal access tokens, use GraphQL and set permissions on the `auth.refresh_tokens` table:
|
||||
|
||||
**Example:** Get all personal access tokens for a user:
|
||||
|
||||
```graphql
|
||||
query personalAccessTokens($userId: uuid!) {
|
||||
authRefreshTokens(where: { _and: [{ userId: { _eq: $userId } }, { type: { _eq: pat } }] }) {
|
||||
id
|
||||
expiresAt
|
||||
metadata
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Example:** Remove a personal access token:
|
||||
|
||||
```graphql
|
||||
mutation removePersonalAccessToken($id: uuid!) {
|
||||
deleteAuthRefreshToken(id: $id) {
|
||||
id
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,53 +0,0 @@
|
||||
---
|
||||
title: Sign In with Phone Number (SMS)
|
||||
sidebar_label: Phone Number (SMS)
|
||||
slug: /authentication/sign-in-with-phone-number-sms
|
||||
image: /img/og/sign-in-with-phone-number-sms.png
|
||||
---
|
||||
|
||||
Follow this guide to sign in users with a phone number (SMS).
|
||||
|
||||
## Configuration
|
||||
|
||||
You need a [Twilio account](https://www.twilio.com/try-twilio) to use this feature because all SMS are sent through Twilio.
|
||||
|
||||
Enable the Phone Number (SMS) sign-in method in the Nhost dashboard under **Settings -> Sign-In Methods -> Phone Number (SMS)**.
|
||||
|
||||
You need to insert the following settings in the Nhost dashboard from Twilio:
|
||||
|
||||
- Account SID
|
||||
- Auth Token
|
||||
- Messaging Service SID (or a Twilio phone number)
|
||||
|
||||
## Sign In
|
||||
|
||||
To sign in users with a phone number is a two-step process:
|
||||
|
||||
1. Send a one-time password (OTP) to the user's phone number.
|
||||
2. The user uses the OTP to sign in.
|
||||
|
||||
```js
|
||||
// Step 1: Send OTP to the user's phone number
|
||||
await nhost.auth.signIn({
|
||||
phoneNumber: '+11233213123'
|
||||
})
|
||||
|
||||
// Step 2: Sign in user using their phone number and OTP
|
||||
await nhost.auth.signIn({
|
||||
phoneNumber: '+11233213123'
|
||||
// highlight-next-line
|
||||
otp: '123456',
|
||||
})
|
||||
```
|
||||
|
||||
The first time a user signs in using a phone number, the user is created. That means you don't need to sign up users before signing in users.
|
||||
|
||||
:::info
|
||||
|
||||
Phone numbers should start with `+` (not `00`) to follow the [E.164 formatting standard](https://en.wikipedia.org/wiki/E.164).
|
||||
|
||||
:::
|
||||
|
||||
## Other SMS Providers
|
||||
|
||||
We only support Twilio for now. If you want support for another SMS provider, please create an issue on [GitHub](https://github.com/nhost/nhost).
|
||||
@@ -1,136 +0,0 @@
|
||||
---
|
||||
title: Sign In with Security Keys
|
||||
sidebar_label: Security Keys
|
||||
slug: /authentication/sign-in-with-security-keys
|
||||
---
|
||||
|
||||
Follow this guide to sign in users with security keys and the WebAuthn API.
|
||||
|
||||
Examples of security keys:
|
||||
|
||||
- [Windows Hello](https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0)
|
||||
- [Apple Touch ID](https://support.apple.com/en-us/HT201371)
|
||||
- [Apple Face ID](https://support.apple.com/en-us/HT208109)
|
||||
- [Yubico security keys](https://www.yubico.com/)
|
||||
- Android Fingerprint sensors
|
||||
|
||||
You can read more about this feature in our [blog post](https://nhost.io/blog/webauthn-sign-in-method)
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable the Security Key sign-in method in the Nhost dashboard under **Settings -> Sign-In Methods -> Security Keys**.
|
||||
|
||||
You need to make sure you also set a valid client URL under **Settings -> Authentication -> Client URL**.
|
||||
|
||||
## Sign Up
|
||||
|
||||
Users must use an email address to sign up with a security key.
|
||||
|
||||
Here's an example of how to sign up a user with a security key with our [JavaScript SDK](/reference/javascript):
|
||||
|
||||
**Example:**: Sign up with a security key:
|
||||
|
||||
```tsx
|
||||
const { error, session } = await nhost.auth.signUp({
|
||||
email: 'joe@example.com',
|
||||
securityKey: true
|
||||
})
|
||||
|
||||
// Something unexpected happened, for instance, the user canceled the process
|
||||
if (error) {
|
||||
console.log(error)
|
||||
return
|
||||
}
|
||||
|
||||
// if there is no error and no session, the user needs to verify their email address.
|
||||
if (!session) {
|
||||
console.log(
|
||||
'You need to verify your email address by clicking the link in the email we sent you.'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
//Sign-up is complete!
|
||||
console.log(session.user)
|
||||
```
|
||||
|
||||
## Sign In
|
||||
|
||||
Once a user signed up with a security key, and verfied their email if needed, they can use it to sign in.
|
||||
|
||||
**Example:** Sign in with a security key:
|
||||
|
||||
```tsx
|
||||
const { error, session } = await nhost.auth.signIn({
|
||||
email: 'joe@example.com',
|
||||
securityKey: true
|
||||
})
|
||||
|
||||
// Something unexpected happened, for instance, the user canceled the process
|
||||
if (error) {
|
||||
console.log(error)
|
||||
return
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
// Something unexpected happened
|
||||
console.log(error)
|
||||
return
|
||||
}
|
||||
|
||||
// User is signed in
|
||||
```
|
||||
|
||||
## Add a Security Key
|
||||
|
||||
Any signed-in user with a verified email can add a security key to their user account. Once a security key is added, the user can use it their email and the security key to sign in.
|
||||
|
||||
It's possible to add multiple security keys to a user account.
|
||||
|
||||
**Example:** Add a security key to a user account:
|
||||
|
||||
```tsx
|
||||
const { key, error } = await nhost.auth.addSecurityKey()
|
||||
|
||||
// Something unexpected happened
|
||||
if (error) {
|
||||
console.log(error)
|
||||
return
|
||||
}
|
||||
|
||||
// Successfully added a new security key
|
||||
console.log(key.id)
|
||||
```
|
||||
|
||||
A nickname can be associated with each security key to make it easier to manage security keys in the future.
|
||||
|
||||
**Example:** Add a security key with a nickname:
|
||||
|
||||
```tsx
|
||||
await nhost.auth.addSecurityKey('iPhone')
|
||||
```
|
||||
|
||||
## List or Remove Security Keys
|
||||
|
||||
To list and remove security keys, use GraphQL and set permissions on the `auth.security_keys` table:
|
||||
|
||||
**Example:** Get all security keys for a user:
|
||||
|
||||
```graphql
|
||||
query securityKeys($userId: uuid!) {
|
||||
authUserSecurityKeys(where: { userId: { _eq: $userId } }) {
|
||||
id
|
||||
nickname
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Example:** Remove a security key:
|
||||
|
||||
```graphql
|
||||
mutation removeSecurityKey($id: uuid!) {
|
||||
deleteAuthUserSecurityKey(id: $id) {
|
||||
id
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "Sign-In Methods",
|
||||
"position": 2
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
title: 'Sign-In Methods'
|
||||
slug: /authentication/sign-in-methods
|
||||
image: /img/og/sign-in-methods.png
|
||||
---
|
||||
|
||||
Nhost Authentication supports the following sign-in methods:
|
||||
|
||||
- [Email and Password](/authentication/sign-in-with-email-and-password)
|
||||
- [Magic Link](/authentication/sign-in-with-magic-link)
|
||||
- [Phone Number (SMS)](/authentication/sign-in-with-phone-number-sms)
|
||||
- [Security Keys (WebAuthn)](/authentication/sign-in-with-security-keys)
|
||||
- [Apple](/authentication/sign-in-with-apple)
|
||||
- [Discord](/authentication/sign-in-with-discord)
|
||||
- [Facebook](/authentication/sign-in-with-facebook)
|
||||
- [GitHub](/authentication/sign-in-with-github)
|
||||
- [Google](/authentication/sign-in-with-google)
|
||||
- [LinkedIn](/authentication/sign-in-with-linkedin)
|
||||
- [Spotify](/authentication/sign-in-with-spotify)
|
||||
- [Twitch](/authentication/sign-in-with-twitch)
|
||||
|
||||
## Enabling sign-in methods during local development
|
||||
|
||||
To enable a sign-in method locally, add variables corresponding to the relevant authentication methods in an `.env.development` file located in the project repository. An overview of available options is available in the [Hasura Auth repository](https://github.com/nhost/hasura-auth/blob/main/docs/environment-variables.md#oauth-environment-variables).
|
||||
@@ -1,46 +0,0 @@
|
||||
---
|
||||
title: Social Providers
|
||||
sidebar_label: Social Providers
|
||||
sidebar_position: 10
|
||||
---
|
||||
|
||||
## Enabling Social Sign-In Provider
|
||||
|
||||
To start with social sign-in, select your project in Nhost Dashboard and go to **Settings -> Sign-In Methods**.
|
||||
|
||||
## Implementing sign-in experience
|
||||
|
||||
Use the [Nhost JavaScript SDK](/reference/javascript) and the `signIn()` method to implement social sign-in for your project.
|
||||
|
||||
**Example**: Sign in a user with [GitHub](/authentication/sign-in-with-github).
|
||||
|
||||
```js
|
||||
nhost.auth.signIn({
|
||||
provider: 'github'
|
||||
})
|
||||
```
|
||||
|
||||
During the sign-in flow, the user is redirected to the provider's website to authenticate. After the user authenticates, they are redirected back to your Nhost project's [**Client URL**](/authentication#client-url) by default. You can change where the user gets redirected to after authentication by passing the `redirectTo` option.
|
||||
|
||||
**Example:** Redirect the user to `https://staging.example.com/welcome` after they complete the sign-in flow.
|
||||
|
||||
```js
|
||||
nhost.auth.signIn({
|
||||
provider: 'github'
|
||||
options: {
|
||||
redirectTo: "https://staging.example.com/welcome",
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
In the example above, it's important to note that the `redirectTo` URL must be part of the [Allowed Redirect URLs](/authentication#allowed-redirect-urls) of your Nhost project.
|
||||
|
||||
## Provider OAuth scopes
|
||||
|
||||
Scopes are a mechanism in OAuth to allow or limit an application's access to a user's account.
|
||||
|
||||
By default, Nhost sets the scope to get the name, email, and avatar URL for each user. Editing scope is not currently supported.
|
||||
|
||||
## Provider OAuth Tokens
|
||||
|
||||
Nhost saves both access and refresh tokens for each user and provider in the `auth.user_providers` table. These tokens can be used to interact with the provider if needed.
|
||||
@@ -1,74 +0,0 @@
|
||||
---
|
||||
title: Tokens
|
||||
sidebar_label: Tokens
|
||||
sidebar_position: 10
|
||||
image: /img/og/tokens.png
|
||||
---
|
||||
|
||||
Nhost Authentication makes use of two types of tokens:
|
||||
|
||||
- **Access token** - used to authenticate a user and access APIs.
|
||||
- **Refresh token** - used to get a new access token.
|
||||
|
||||
Users get both an access token and a refresh token when they sign in.
|
||||
|
||||
:::info
|
||||
If you're using the [Nhost JavaScript client](/reference/javascript), all tokens are automatically set and updated for you. But it can still be good to understand how they work.
|
||||
:::
|
||||
|
||||
## Access Token
|
||||
|
||||
An access token (also called [JSON Web Token or JWT](https://en.wikipedia.org/wiki/JSON_Web_Token)) contains information about the user such as the user id. Users send this token to the Nhost services (GraphQL, Auth, Storage, Serverless Functions) to let the services know who's making the request so the services can verify the user's identity and resolve the correct permissions.
|
||||
|
||||
The access token is added as an `Authorization` header when making a request, like this:
|
||||
|
||||
```http title="Header"
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
Here's an example of an encoded access token:
|
||||
|
||||
```
|
||||
eyJhbGciOiJIUzI1NiJ9.eyJodHRwczovL2hhc3VyYS5pby9qd3QvY2xhaW1zIjp7IngtaGFzdXJhLWFsbG93ZWQtcm9sZXMiOlsibWUiLCJ1c2VyIl0sIngtaGFzdXJhLWRlZmF1bHQtcm9sZSI6InVzZXIiLCJ4LWhhc3VyYS11c2VyLWlkIjoiMTUzODYzZjktZTQwMC00Njg2LTgyMTEtMzI0OGNjYWY2MGJhIiwieC1oYXN1cmEtdXNlci1pcy1hbm9ueW1vdXMiOiJmYWxzZSJ9LCJzdWIiOiIxNTM4NjNmOS1lNDAwLTQ2ODYtODIxMS0zMjQ4Y2NhZjYwYmEiLCJpc3MiOiJoYXN1cmEtYXV0aCIsImlhdCI6MTY1Mzg5MjA5NCwiZXhwIjoxNjUzODkyOTk0fQ.9nVL2Lj8KWBW3WrjJr4tPNH3_29qJKKKSDRNYebhiHI
|
||||
```
|
||||
|
||||
The decoded payload of this access token is a JSON object that looks like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"https://hasura.io/jwt/claims": {
|
||||
"x-hasura-allowed-roles": ["me", "user"],
|
||||
"x-hasura-default-role": "user",
|
||||
"x-hasura-user-id": "153863f9-e400-4686-8211-3248ccaf60ba",
|
||||
"x-hasura-user-is-anonymous": "false"
|
||||
},
|
||||
"sub": "153863f9-e400-4686-8211-3248ccaf60ba",
|
||||
"iss": "hasura-auth",
|
||||
"iat": 1653892094,
|
||||
"exp": 1653892994
|
||||
}
|
||||
```
|
||||
|
||||
The token contains information about the user id, default role, allowed roles, if the user is anonymous or not, and other metadata.
|
||||
|
||||
The claims under `https://hasura.io/jwt/claims` are the same claims that are used by the GraphQL API to create [permissions](/graphql/permissions). The claims (`x-hasura-*`) are also called permission variables. It's possible to add more [permission variables](/graphql/permissions#permission-variables) to the access token.
|
||||
|
||||
:::info
|
||||
You can manually decode an access token using [JWT.io](https://jwt.io/).
|
||||
:::
|
||||
|
||||
The token is cryptographically signed by Nhost Auth, which means that all other Nhost services can trust the information in the token.
|
||||
|
||||
:::info
|
||||
Use the `NHOST_JWT_SECRET` [system environment variable](/platform/environment-variables#system-environment-variables) to verify access tokens in [Serverless Functions](/serverless-functions). Here's a guide on how to [Get the authenticated user in a Serverless Function](https://github.com/nhost/nhost/discussions/278).
|
||||
:::
|
||||
|
||||
The access token can not be revoked. Instead, the token is only valid for 15 minutes. The user can get a new access token by using the refresh token.
|
||||
|
||||
## Refresh Token
|
||||
|
||||
A refresh token is used to request a new access token. Refresh tokens are long-lived tokens stored in the database in the `auth.refresh_tokens` table.
|
||||
|
||||
Refresh tokens are valid for 30 days.
|
||||
|
||||
To revoke a refresh token, simply delete it from the database.
|
||||
@@ -1,162 +0,0 @@
|
||||
---
|
||||
title: Users
|
||||
sidebar_label: Users
|
||||
sidebar_position: 1
|
||||
image: /img/og/users.png
|
||||
---
|
||||
|
||||
Users are stored in the `auth.users` table in the [database](/database).
|
||||
|
||||
## Creating Users
|
||||
|
||||
Users should be created using the sign-up or sign-in flows as described under [sign-in methods](/authentication/sign-in-methods).
|
||||
|
||||
- **Never** create users directly via GraphQL or database, unless you [import users](#import-users) from an external system.
|
||||
- **Never** modify the database schema for the `auth.users` table.
|
||||
- **Never** modify the GraphQL root queries or fields for any of the tables in the `auth` schema.
|
||||
|
||||
You're allowed to:
|
||||
|
||||
- Add and remove your GraphQL relationships for the `users` table and other tables in the `auth` schema.
|
||||
- Create, edit and delete permissions for the `users` table and other tables in the `auth` schema.
|
||||
|
||||
## Roles
|
||||
|
||||
Each user has one **default role** and an array of **allowed roles**. These roles are used to resolve permissions for requests to [GraphQL](/graphql/permissions) and [Storage](/storage#permissions).
|
||||
|
||||
When the user makes a request, only one role is used to resolve permissions. The default role is used if no role is explicitly specified. Users can only make requests using the default role or one of the allowed roles.
|
||||
|
||||
You can manage users' default roles and allowed roles in the Dashboard at **Auth**.
|
||||
|
||||
### Default Role
|
||||
|
||||
The default role is used when no role is specified in the request. By default, users' default role is `user`.
|
||||
|
||||
You can change what the default role for new users should be at **Settings -> Roles and Permissions**.
|
||||
|
||||
### Allowed Roles
|
||||
|
||||
Allowed roles are roles the user is allowed to use when making a request. Usually, you would change the role from `user` (the default role) to some other role because you want to use a different role to resolve permissions for a particular request.
|
||||
|
||||
By default, users have two allowed roles:
|
||||
|
||||
- `user` (also the default role)
|
||||
- `me`
|
||||
|
||||
You can change what the default role for new users should be at **Settings -> Roles and Permissions**.
|
||||
|
||||
#### Assign Allowed Roles
|
||||
|
||||
It's possible to give users a subset of allowed roles during signup.
|
||||
|
||||
**Example:** Only give the `user` role (without the `me` role) for the user's allowed roles:
|
||||
|
||||
```js
|
||||
await nhost.auth.signUp({
|
||||
email: 'joe@example.com',
|
||||
password: 'secret-password'
|
||||
options: {
|
||||
allowedRoles: ['user']
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Set Role for GraphQL Requests
|
||||
|
||||
When no request role is specified, the user's default role will be used:
|
||||
|
||||
```js
|
||||
await nhost.graphql.request(QUERY, {})
|
||||
```
|
||||
|
||||
If you want to make a GraphQL request using a specific role, you can do so by using the `x-hasura-role` header, like this:
|
||||
|
||||
```js
|
||||
await nhost.graphql.request(
|
||||
QUERY,
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
'x-hasura-role': 'me'
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
If the request is not part of the user's allowed roles, the request will fail.
|
||||
|
||||
## Metadata
|
||||
|
||||
You can store custom information about the user in the `metadata` column of the `users` table. The `metadata` column is of type JSONB so any JSON data can be stored.
|
||||
|
||||
**Example:** Add metadata to a user during sign-up:
|
||||
|
||||
```js
|
||||
await nhost.auth.signUp({
|
||||
email: 'joe@example.com',
|
||||
password: 'secret-password',
|
||||
options: {
|
||||
metadata: {
|
||||
birthYear: 1989,
|
||||
town: 'Stockholm',
|
||||
likes: ['Postgres', 'GraphQL', 'Hasura', 'Authentication', 'Storage', 'Serverless Functions']
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Get User Information using GraphQL
|
||||
|
||||
**Example:** Get all users.
|
||||
|
||||
```graphql
|
||||
query {
|
||||
users {
|
||||
id
|
||||
displayName
|
||||
email
|
||||
metadata
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Example:** Get a single user.
|
||||
|
||||
```graphql
|
||||
query {
|
||||
user(id: "<user-id>") {
|
||||
id
|
||||
displayName
|
||||
email
|
||||
metadata
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Import Users
|
||||
|
||||
If you have users in a different system, you can import them into Nhost. When importing users you should insert the users directly into the database instead of using the authentication endpoints (`/signup/email-password`) to avoid sending unnecessary transactional emails.
|
||||
|
||||
It's possible to insert users via GraphQL or SQL.
|
||||
|
||||
### GraphQL
|
||||
|
||||
Make a GraphQL request to insert a user like this:
|
||||
|
||||
```graphql
|
||||
mutation insertUser($user: users_insert_input!) {
|
||||
insertUser(object: $user) {
|
||||
id
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### SQL
|
||||
|
||||
Connect directly to the database and insert a user like this:
|
||||
|
||||
```sql
|
||||
INSERT INTO auth.users (id, email, display_name, password_hash, ..) VALUES ('<user-id>', '<email>', '<display-name>', '<password-hash>', ..);
|
||||
```
|
||||
|
||||
Passwords are hashed using [bcrypt](https://en.wikipedia.org/wiki/Bcrypt).
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "CLI",
|
||||
"position": 9
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: Nhost CLI
|
||||
sidebar_label: Overview
|
||||
sidebar_position: 1
|
||||
image: /img/og/cli.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
The Nhost CLI is used to run and develop your projects locally and deploy changes to the Nhost Platform.
|
||||
|
||||
## Installation
|
||||
|
||||
Install the CLI with:
|
||||
|
||||
```bash
|
||||
sudo curl -L https://raw.githubusercontent.com/nhost/cli/main/get.sh | bash
|
||||
```
|
||||
|
||||
## Updates
|
||||
|
||||
To update the Nhost CLI to its latest version, run the following command:
|
||||
|
||||
```bash
|
||||
sudo nhost sw upgrade
|
||||
```
|
||||
|
||||
### Dependencies
|
||||
|
||||
- [Docker](https://www.docker.com/get-started)
|
||||
|
||||
## See also
|
||||
|
||||
- [Local Development](/cli/local-development)
|
||||
- [Migrate to Nhost Config](/cli/migrate-config)
|
||||
- [Multiple Projects in Parallel](/cli/multiple-projects)
|
||||
- [CLI Documentation](/cli)
|
||||
@@ -1,208 +0,0 @@
|
||||
---
|
||||
title: 'Local Development'
|
||||
sidebar_label: 'Local Development'
|
||||
sidebar_position: 2
|
||||
image: /img/og/get-started-with-nhost-cli.png
|
||||
---
|
||||
|
||||
Nhost's command-line interface (CLI) lets you run a complete Nhost development environment locally with the following services: PostgreSQL database, Hasura, Authentication, Storage (MinIO), Serverless Functions, and Emails (Mailhog).
|
||||
|
||||
|
||||
## Dependencies
|
||||
|
||||
- [Git](https://git-scm.com/downloads)
|
||||
- [Docker](https://www.docker.com/get-started)
|
||||
|
||||
## Login to Nhost
|
||||
|
||||
```bash
|
||||
nhost login
|
||||
```
|
||||
|
||||
:::info
|
||||
If you used GitHub to register, you will have to first set a password in your [account page](https://app.nhost.io/account).
|
||||
:::
|
||||
|
||||
|
||||
## Initialize local project
|
||||
|
||||
Let's start by creating a directory to hold your project.
|
||||
|
||||
```bash
|
||||
mkdir my-project
|
||||
cd my-project
|
||||
```
|
||||
|
||||
We can now initialize and create the necessary project configuration.
|
||||
|
||||
```bash
|
||||
nhost init
|
||||
```
|
||||
|
||||
`nhost init` creates all the configuration necessary for your project, including database migrations and Hasura metadata.
|
||||
|
||||
|
||||
We can now start your project with `nhost up`.
|
||||
|
||||
```bash
|
||||
nhost up
|
||||
```
|
||||
|
||||
Once all services are up and running, the following information is displayed for your project:
|
||||
|
||||
```bash
|
||||
Nhost development environment started.
|
||||
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5432/local
|
||||
- Hasura: https://local.hasura.nhost.run
|
||||
- GraphQL: https://local.graphql.nhost.run
|
||||
- Auth: https://local.auth.nhost.run
|
||||
- Storage: https://local.storage.nhost.run
|
||||
- Functions: https://local.functions.nhost.run
|
||||
- Dashboard: https://local.dashboard.nhost.run
|
||||
- Mailhog: https://local.mailhog.nhost.run
|
||||
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
|
||||
```
|
||||
|
||||
You can use `nhost down` at any time to tear down your environment.
|
||||
|
||||
### Access your project's services
|
||||
|
||||
To test that the services are running, let's curl the Auth endpoint and get its version:
|
||||
|
||||
```bash
|
||||
curl https://local.auth.nhost.run/v1/version
|
||||
|
||||
{"version":"v0.20.1"}
|
||||
```
|
||||
|
||||
Hurrah! Auth seems to be running on v0.20.1.
|
||||
|
||||
We can also test that Postgres is running as expected by using `psql` (or your favourite Postgres client).
|
||||
|
||||
```bash
|
||||
psql postgres://postgres:postgres@localhost:5432/local
|
||||
|
||||
psql (14.8 (Ubuntu 14.8-0ubuntu0.22.04.1), server 14.6 (Debian 14.6-1.pgdg110+1))
|
||||
Type "help" for help.
|
||||
|
||||
local=#
|
||||
```
|
||||
|
||||
## Database Migrations and Metadata Changes
|
||||
|
||||
All changes to your project should be tested locally first before deploying to your users. In this guide, we will be creating a database migration and setting permissions.
|
||||
|
||||
### Migration
|
||||
|
||||
Let's create a new table called `messages`, with the following columns:
|
||||
|
||||
- id (UUID)
|
||||
- text (Text)
|
||||
- author_id (UUID)
|
||||
- created_at (Timestamp)
|
||||
|
||||
There are other ways to generate a migration, here we will use the local Nhost Dashboard running on `https://local.dashboard.nhost.run/local/local`. Please head to the `database` tab and add the columns as follows:
|
||||
|
||||
|
||||

|
||||
|
||||
To confirm that the migration was correctly generated with the correct SQL:
|
||||
|
||||
```bash
|
||||
cat nhost/migrations/default/1685452095884_create_table_public_messages/up.sql
|
||||
|
||||
CREATE TABLE public.messages (id uuid DEFAULT gen_random_uuid() NOT NULL, text text NOT NULL, author_id uuid NOT NULL, created_at timestamp DEFAULT now() NOT NULL, PRIMARY KEY (id));
|
||||
```
|
||||
|
||||
Now is a good time to commit the new migration.
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m 'add database migration to create the table `messages`'
|
||||
```
|
||||
|
||||
### Metadata
|
||||
|
||||
Metadata is used to track the state of the API, permissions, event triggers, remote schemas, etc. In this guide, we will use permissions to show how metadata is tracked.
|
||||
|
||||
Again on the `database` tab of the Nhost Dashboard, click on the 3 dots right next to the table name and choose "Edit Permissions" to open the permissions editor.
|
||||
|
||||

|
||||
|
||||
Here we have access to a matrix of permissions for all available roles and actions. We want to set a permission to the `user` role and `insert` action as follows:
|
||||
|
||||

|
||||
|
||||
We defined a simple permission to allow a `user` to insert or create messages. We can look at the underlying metadata that tracks it.
|
||||
|
||||
```bash
|
||||
cat nhost/metadata/databases/default/tables/public_messages.yaml
|
||||
|
||||
table:
|
||||
name: messages
|
||||
schema: public
|
||||
insert_permissions:
|
||||
- role: public
|
||||
permission:
|
||||
check:
|
||||
author_id:
|
||||
_eq: X-Hasura-User-Id
|
||||
set:
|
||||
author_id: X-Hasura-User-Id
|
||||
columns:
|
||||
- text
|
||||
```
|
||||
|
||||
As before, we can now commit this change:
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m 'add permission for user insert messages'
|
||||
```
|
||||
|
||||
## Deploy your Project to Nhost
|
||||
|
||||
We've been developing your project locally, introducing changes via the Dashboard, which in turn creates the actual database migrations and metadata changes that can be properly versioned and tracked. It's time to deploy your project to the Nhost Platform using Git. If you haven't already, please head to [Nhost](https://app.nhost.io) and create a project to deploy to. You will also need to connect a GitHub repository to it for automatic deployments with Git.
|
||||
|
||||
### Link your project
|
||||
|
||||
It's time to link, or associate, your local project to the remote one:
|
||||
|
||||
```bash
|
||||
nhost link
|
||||
|
||||
│ │ │ │ │
|
||||
# │ Subdomain │ Project │ Workspace │ Region │
|
||||
1 │ kgrbyupffiamgqwnovkb │ local-development │ Nhost │ eu-central-1 │
|
||||
2 │ odtxlexktkcwdynjssqg │ nbp │ Nuno's Workspace │ eu-central-1 │
|
||||
│ │ │ │ │
|
||||
- Select the workspace # to link: 1
|
||||
- Enter project subdomain to confirm: kgrbyupffiamgqwnovkb
|
||||
```
|
||||
|
||||
You have now successfully linked your local project to a hosted project running on the Nhost Cloud.
|
||||
|
||||
The final step is to push all changes to GitHub which will trigger a new deployment on Nhost.
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git push -u origin main
|
||||
```
|
||||
|
||||
To check out your deployment, head over to the **Deployments** tab (https://app.nhost.io).
|
||||
|
||||

|
||||
|
||||
You should now have the same `messages` table (and permissions) on your production instance!
|
||||
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
---
|
||||
title: 'Migrate Existing Projects'
|
||||
sidebar_label: 'Migrate to Nhost Config'
|
||||
sidebar_position: 3
|
||||
image: /img/og/get-started-with-nhost-cli.png
|
||||
---
|
||||
|
||||
|
||||
If you want to migrate an existing project you need to:
|
||||
|
||||
1. Go into your project's folder:
|
||||
|
||||
```
|
||||
$ cd /path/to/existingproject
|
||||
```
|
||||
|
||||
2. Login:
|
||||
|
||||
```
|
||||
$ nhost login
|
||||
- email: david@nhost.io
|
||||
- password:
|
||||
Authenticating
|
||||
Successfully logged in, creating PAT
|
||||
Successfully created PAT
|
||||
Storing PAT for future user
|
||||
```
|
||||
|
||||
3. Link your project:
|
||||
|
||||
```
|
||||
❯ nhost link
|
||||
│ │ │ │ │
|
||||
# │ Subdomain │ Project │ Workspace │ Region │
|
||||
1 │ lrkadqfanxgmscttabiv │ demo │ david-yirq │ eu-central-1 │
|
||||
│ │ │ │ │
|
||||
- Select # the workspace to link: 1
|
||||
- Enter project subdomain to confirm: lrkadqfanxgmscttabiv
|
||||
```
|
||||
|
||||
4. Pull the configuration from the cloud:
|
||||
|
||||
```
|
||||
$ nhost config pull
|
||||
- /path/to/existingproject/nhost/nhost.toml already exists. Do you want to overwrite it? [y/N] y
|
||||
- /path/to/existingproject/.secrets already exists. Do you want to overwrite it? [y/N] y
|
||||
Pulling config from Nhost...
|
||||
Getting secrets list from Nhost...
|
||||
Adding .secrets to .gitignore...
|
||||
Success!
|
||||
- Review `nhost/nhost.toml` and make sure there are no secrets before you commit it to git.
|
||||
- Review `.secrets` file and set your development secrets
|
||||
- Review `.secrets` was added to .gitignore
|
||||
```
|
||||
|
||||
5. Follow the instructions on screen to ensure your configuration contains no secrets and you don't commit sensitive information to git.
|
||||
|
||||
6. Profit:
|
||||
|
||||
```
|
||||
$ nhost up
|
||||
Verifying configuration...
|
||||
Configuration is valid!
|
||||
Setting up Nhost development environment...
|
||||
Starting Nhost development environment...
|
||||
[+] Running 11/11
|
||||
✔ Network existingproject_default Created 0.0s
|
||||
✔ Container existingproject-minio-1 Healthy 13.9s
|
||||
✔ Container existingproject-postgres-1 Healthy 13.9s
|
||||
✔ Container existingproject-traefik-1 Healthy 13.9s
|
||||
✔ Container existingproject-dashboard-1 Healthy 13.9s
|
||||
✔ Container existingproject-mailhog-1 Healthy 13.9s
|
||||
✔ Container existingproject-functions-1 Healthy 13.9s
|
||||
✔ Container existingproject-graphql-1 Healthy 13.8s
|
||||
✔ Container existingproject-console-1 Healthy 18.8s
|
||||
✔ Container existingproject-storage-1 Healthy 13.8s
|
||||
✔ Container existingproject-auth-1 Healthy 18.8s
|
||||
Applying migrations...
|
||||
INFO nothing to apply on database: default
|
||||
Nhost development environment started.
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5432/postgres
|
||||
- Hasura: https://local.hasura.nhost.run
|
||||
- GraphQL: https://local.graphql.nhost.run
|
||||
- Auth: https://local.auth.nhost.run
|
||||
- Storage: https://local.storage.nhost.run
|
||||
- Functions: https://local.functions.nhost.run
|
||||
- Dashboard: https://local.dashboard.nhost.run
|
||||
- Mailhog: https://local.mailhog.nhost.run
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
```
|
||||
@@ -1,107 +0,0 @@
|
||||
---
|
||||
title: 'Running multiple projects at the same time'
|
||||
sidebar_label: 'Multiple Projects'
|
||||
sidebar_position: 4
|
||||
image: /img/og/get-started-with-nhost-cli.png
|
||||
---
|
||||
|
||||
By default the name of the project is going to be the folder of the root of your project and it's goint to run on port 443 (https) and 5432 (postgres). If you need to run multiple projects or multiple instances of the same project at the same time you may need to override those. For instance:
|
||||
|
||||
```
|
||||
$ nhost up
|
||||
Verifying configuration...
|
||||
Configuration is valid!
|
||||
Setting up Nhost development environment...
|
||||
Starting Nhost development environment...
|
||||
[+] Running 11/11
|
||||
✔ Network existingproject_default Created 0.0s
|
||||
✔ Container existingproject-minio-1 Healthy 13.9s
|
||||
✔ Container existingproject-postgres-1 Healthy 13.9s
|
||||
✔ Container existingproject-traefik-1 Healthy 13.9s
|
||||
✔ Container existingproject-dashboard-1 Healthy 13.9s
|
||||
✔ Container existingproject-mailhog-1 Healthy 13.9s
|
||||
✔ Container existingproject-functions-1 Healthy 13.9s
|
||||
✔ Container existingproject-graphql-1 Healthy 13.8s
|
||||
✔ Container existingproject-console-1 Healthy 18.8s
|
||||
✔ Container existingproject-storage-1 Healthy 13.8s
|
||||
✔ Container existingproject-auth-1 Healthy 18.8s
|
||||
Applying migrations...
|
||||
INFO nothing to apply on database: default
|
||||
Nhost development environment started.
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5432/postgres
|
||||
- Hasura: https://local.hasura.nhost.run
|
||||
- GraphQL: https://local.graphql.nhost.run
|
||||
- Auth: https://local.auth.nhost.run
|
||||
- Storage: https://local.storage.nhost.run
|
||||
- Functions: https://local.functions.nhost.run
|
||||
- Dashboard: https://local.dashboard.nhost.run
|
||||
- Mailhog: https://local.mailhog.nhost.run
|
||||
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
|
||||
$ nhost --project-name alternativeproject dev up --http-port 8433 --postgres-port 5433
|
||||
Verifying configuration...
|
||||
Configuration is valid!
|
||||
Setting up Nhost development environment...
|
||||
Starting Nhost development environment...
|
||||
[+] Running 13/13
|
||||
✔ Network alternativeproject_default Created 0.0s
|
||||
✔ Volume "alternativeproject_root_node_modules" Created 0.0s
|
||||
✔ Volume "alternativeproject_functions_node_modules" Created 0.0s
|
||||
✔ Container alternativeproject-mailhog-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-functions-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-dashboard-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-postgres-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-traefik-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-minio-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-graphql-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-storage-1 Healthy 13.7s
|
||||
✔ Container alternativeproject-console-1 Healthy 18.7s
|
||||
✔ Container alternativeproject-auth-1 Healthy 18.2s
|
||||
Applying migrations...
|
||||
INFO nothing to apply on database: default
|
||||
Nhost development environment started.
|
||||
URLs:
|
||||
- Postgres: postgres://postgres:postgres@localhost:5433/postgres
|
||||
- Hasura: https://local.hasura.nhost.run:8433
|
||||
- GraphQL: https://local.graphql.nhost.run:8433
|
||||
- Auth: https://local.auth.nhost.run:8433
|
||||
- Storage: https://local.storage.nhost.run:8433
|
||||
- Functions: https://local.functions.nhost.run:8433
|
||||
- Dashboard: https://local.dashboard.nhost.run:8433
|
||||
- Mailhog: https://local.mailhog.nhost.run:8433
|
||||
|
||||
SDK Configuration:
|
||||
Subdomain: local
|
||||
Region: (empty)
|
||||
|
||||
Run `nhost up` to reload the development environment
|
||||
Run `nhost down` to stop the development environment
|
||||
Run `nhost logs` to watch the logs
|
||||
```
|
||||
|
||||
From now on you can operate on each one of them accordingly by specifying `--project-name`:
|
||||
|
||||
```
|
||||
$ nhost --project-name alternativeproject dev logs auth
|
||||
alternativeproject-auth-1 |
|
||||
alternativeproject-auth-1 | > hasura-auth@0.19.1 start /app
|
||||
alternativeproject-auth-1 | > node ./dist/start.js
|
||||
alternativeproject-auth-1 |
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Log level: info"}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Waiting for Hasura to be ready..."}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Hasura is ready"}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Applying SQL migrations..."}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"SQL migrations applied"}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Applying metadata..."}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Metadata applied"}
|
||||
alternativeproject-auth-1 | {"level":"info","message":"Running on port 4000"}
|
||||
```
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
---
|
||||
title: 'Configuration Overlays'
|
||||
sidebar_label: 'Configuration Overlays'
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
Nhost uses a single configuration file to configure both cloud projects and the local development environment, ensuring a near-identical replica of the production environment. This approach also simplifies connecting a repository to multiple projects, keeping them in sync with minimal effort. However, in cases where minor differences need to be accommodated, Nhost offers overlays - files containing operations to modify the configuration file:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"op": "replace",
|
||||
"path": "/auth/method/emailPassword/emailVerificationRequired",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"op": "replace",
|
||||
"path": "/auth/redirections/clientUrl",
|
||||
"value": "https://staging.myapp.io"
|
||||
},
|
||||
{
|
||||
"op": "add",
|
||||
"path": "/global/environment/3",
|
||||
"value": {
|
||||
"name": "ENVIRONMENT",
|
||||
"value": "staging"
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
The overlay above will perform the following changes to the configuration file:
|
||||
|
||||
1. Disable email verification
|
||||
2. Set the correct client URL for the staging environment
|
||||
3. Add the environment variable `ENVIRONMENT=staging`
|
||||
|
||||
:::info
|
||||
Overlays are based on [RFC6902](https://www.rfc-editor.org/rfc/rfc6902)
|
||||
:::
|
||||
|
||||
It's important to note that overlays in Nhost do not modify the original files, but rather manipulate the resulting configuration at runtime. This allows multiple environments to safely share the same base configuration and rely on the overlay to accommodate differences. Additionally, changes to the base configuration file will propagate to all environments unless an overlay operation prevents it, making overlays a convenient and efficient way to manage configuration differences.
|
||||
|
||||
## Creating Overlays
|
||||
|
||||
You can create overlays with the CLI command `nhost config edit [--subdomain $SUBDOMAIN]`:
|
||||
|
||||

|
||||
|
||||
:::info
|
||||
If you need to create an overlay for your local development environment remember to use `local` as subdomain
|
||||
:::
|
||||
|
||||
This will open an editor with the configuration for your `$SUBDOMAIN`:
|
||||
|
||||

|
||||
|
||||
You can perform as many changes as needed using overlays. For example, you can add an environment variable, enable Hasura remote permissions, and change the client URL.
|
||||
|
||||

|
||||
|
||||
You can verify the overlay by checking the file `nhost/overlays/$SUBDOMAIN.json`
|
||||
|
||||

|
||||
|
||||
## Viewing Configuration
|
||||
|
||||
To verify that your final configuration is correct, you can use the command `nhost config show [--subdomain $SUBDOMAIN]`. This command will apply the specified overlay (if it exists) and render the configuration using the local secrets.
|
||||
|
||||

|
||||
|
||||
## Validating Configuration
|
||||
|
||||
Finally, you can validate your configuration overlay with the command `nhost config validate [--subdomain $SUBDOMAIN]`
|
||||
|
||||

|
||||
@@ -1,84 +0,0 @@
|
||||
---
|
||||
title: 'Seeds'
|
||||
sidebar_label: 'Seeds'
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
When developing locally, it is very useful to work with a known set of data as it can simplify testing and development, especially when working in larger teams with multiple developers.
|
||||
|
||||
With the CLI, it is easy to extract data from an existing environment and generate a "seed" that can be shared and used to pre-populate any development environment as it initializes.
|
||||
|
||||
As mentioned before, you can create a seed from any environment. In this guide, we will assume that we have already started a local development with a table called "animals". At this point, we can add some data ourselves as usual. Once we are satisfied and have the data we want, we can run the following command to create a seed:
|
||||
|
||||
```
|
||||
$ nhost dev hasura seed create some-initial-data \
|
||||
--endpoint https://local.hasura.nhost.run \
|
||||
--admin-secret nhost-admin-secret \
|
||||
--database-name default \
|
||||
--from-table animals
|
||||
|
||||
INFO created seed file successfully file=/app/seeds/default/1685692310174_some-initial-data.sql
|
||||
```
|
||||
|
||||
:::info
|
||||
In the previous command, we instructed the CLI to create a seed named `some-initial-data` while specifying the connection parameters for our local environment. You could also extract data from a cloud project by specifying the correct parameters. Finally, we are only extracting data from the `animals` table, but you could also extract data from any other table or even from all tables
|
||||
:::
|
||||
|
||||
We can now inspect the file and see its contents:
|
||||
|
||||
```
|
||||
$ cat nhost/seeds/default/1685692310174_some-initial-data.sql
|
||||
SET check_function_bodies = false;
|
||||
INSERT INTO public.animals (id, created_at, updated_at, name) VALUES ('d50ff2e8-ec2a-496b-a2e6-a50eecccdb16', '2023-05-16 14:01:59.072576+00', '2023-05-16 14:01:59.072576+00', 'dog');
|
||||
INSERT INTO public.animals (id, created_at, updated_at, name) VALUES ('8224ec02-6fed-48ff-8c06-6c36298d0fd0', '2023-05-16 14:02:06.300074+00', '2023-05-16 14:02:06.300074+00', 'cat');
|
||||
```
|
||||
|
||||
Now, when you start a new development environment you can pass the `--apply-seeds` argument to pre-populate your environment with the seeds:
|
||||
|
||||
|
||||
```
|
||||
$ nhost up --apply-seeds
|
||||
Setting up Nhost development environment...
|
||||
Starting Nhost development environment...
|
||||
|
||||
(...) omitted for brevity
|
||||
|
||||
Applying migrations...
|
||||
INFO migrations applied on database: default
|
||||
Applying metadata...
|
||||
INFO Metadata applied
|
||||
Applying seeds...
|
||||
INFO Seed data planted for database: default
|
||||
|
||||
(...) omitted for brevity
|
||||
```
|
||||
|
||||
Or you could also apply the seeds yourself after starting nhost:
|
||||
|
||||
```
|
||||
$ nhost up
|
||||
Setting up Nhost development environment...
|
||||
Starting Nhost development environment...
|
||||
|
||||
(...) omitted for brevity
|
||||
|
||||
Applying migrations...
|
||||
INFO migrations applied on database: default
|
||||
Applying metadata...
|
||||
INFO Metadata applied
|
||||
|
||||
(...) omitted for brevity
|
||||
|
||||
$ nhost dev hasura seed apply \
|
||||
--endpoint https://local.hasura.nhost.run \
|
||||
--admin-secret nhost-admin-secret \
|
||||
--database-name default
|
||||
INFO Help us improve Hasura! The cli collects anonymized usage stats which
|
||||
allow us to keep improving Hasura at warp speed. To opt-out or read more,
|
||||
visit https://hasura.io/docs/latest/graphql/core/guides/telemetry.html
|
||||
INFO Seeds planted
|
||||
```
|
||||
|
||||
:::info
|
||||
Seeds are different from migrations because seeds are not automatically applied. If there is data that you want to have in all of your environments, it is best to use a database migration.
|
||||
:::
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "Database",
|
||||
"position": 4
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
---
|
||||
title: 'Event triggers'
|
||||
sidebar_position: 2
|
||||
image: /img/og/event-triggers.png
|
||||
---
|
||||
|
||||
Event Triggers enable you to invoke webhooks when a database event happens. Event Triggers are typically used to do post-processing tasks, using custom backend code, based on database events.
|
||||
|
||||
Event Triggers are associated with a specific table in the database and the following event types are available:
|
||||
|
||||
- **INSERT** - A row is inserted into a table.
|
||||
- **UPDATE** - A row is updated in a table.
|
||||
- **DELETE** - A row is deleted from a table.
|
||||
|
||||
:::info
|
||||
|
||||
It's currently only possible to create Event Triggers in the Hasura Console. We're working on adding support for creating Event Triggers in the Nhost Dashboard.
|
||||
|
||||
:::
|
||||
|
||||
### Example Use Case
|
||||
|
||||
Let's say you're building an e-commerce application and you want to send an email to the customer when a new order is placed. Orders are stored in the `orders` table in your database.
|
||||
|
||||
To send out an email every time a new order is placed, you create an event trigger that listens for the `INSERT` event on the `orders` table. Now every time an order is placed, the event trigger invokes a webhook with the order information, and the webhook sends out the email.
|
||||
|
||||
## Create Event Trigger
|
||||
|
||||
Event Triggers are managed in the Hasura Console. Select **Events** in the main menu and click **Create** to add an Event Trigger.
|
||||
|
||||
<video width="99%" autoPlay muted loop controls="true">
|
||||
<source src="/videos/hasura-create-event-trigger.mp4" type="video/mp4" />
|
||||
</video>
|
||||
|
||||
## Event Triggers and Serverless Functions
|
||||
|
||||
Event Triggers and [Serverless Functions](/serverless-functions) are a perfect combination to build powerful database-backend logic. Every Serverless Function is exposed as an HTTP endpoint and can be used as a webhook for Event Triggers.
|
||||
|
||||
### Format
|
||||
|
||||
When using Serverless Functions as webhooks you should configure the webhook using a combination of environment variables and endpoints like this:
|
||||
|
||||
```
|
||||
{{NHOST_FUNCTIONS_URL}}/orders-insert-send-email
|
||||
```
|
||||
|
||||

|
||||
|
||||
The `NHOST_FUNCTIONS_URL` is a [system environment variable](/platform/environment-variables#system-environment-variables) and available in production and in development environments using the [CLI](/cli).
|
||||
|
||||
### Security
|
||||
|
||||
To make sure incoming requests to your webhook comes from Hasura, and not some malicious third party, you can use a shared webhook secret between Hasura and your webhook handler (e.g. your Serverless Function).
|
||||
|
||||
It is recommended to use the `NHOST_WEBHOOK_SECRET`, which is a [system environment variable](/platform/environment-variables#system-environment-variables) and available in production and in development environments using the [CLI](/cli). The `NHOST_WEBHOOK_SECRET` is available both in Hasura and in every Serverless Function.
|
||||
|
||||
To set this up is a two-step process:
|
||||
|
||||
- Step 1: Add the header `nhost-webhook-secret` with the value `NHOST_WEBHOOK_SECRET` (From env var) when creating the Event Trigger in the Hasura Console.
|
||||
|
||||

|
||||
|
||||
- Step 2: Check the header `nhost-webhook-secret` for incoming requests and make sure the header is the same as the environment variable `NHOST_WEBHOOK_SECRET`.
|
||||
|
||||
Here is an example of how to check the header in a Serverless Function:
|
||||
|
||||
```js
|
||||
export default async function handler(req, res) {
|
||||
// Check header to make sure the request comes from Hasura
|
||||
if (req.headers['nhost-webhook-secret'] !== process.env.NHOST_WEBHOOK_SECRET) {
|
||||
return res.status(400).send('Incorrect webhook secret')
|
||||
}
|
||||
|
||||
// Do something
|
||||
// Example:
|
||||
// - Send an email
|
||||
// - Create a subscription in Stripe
|
||||
// - Generate a PDF
|
||||
// - Send a message to Slack or Discord
|
||||
// - Update some data in the database
|
||||
|
||||
console.log(JSON.stringify(req.body, null, 2))
|
||||
|
||||
return res.send('OK')
|
||||
}
|
||||
```
|
||||
|
||||
The `NHOST_WEBHOOK_SECRET` is a [system environment variable](/platform/environment-variables#system-environment-variables) and available in production and in development environments using the [CLI](/cli).
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Read the full [Event Triggers documentation from Hasura](https://hasura.io/docs/latest/graphql/core/event-triggers/index/).
|
||||
- Learn about the [GraphQL API](/graphql).
|
||||
@@ -1,169 +0,0 @@
|
||||
---
|
||||
title: 'Database'
|
||||
sidebar_position: 1
|
||||
sidebar_label: 'Overview'
|
||||
image: /img/og/database.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
Every Nhost project comes with its own [Postgres database](https://postgres.org/). Postgres is the world's most advanced open-source relational database and it's the most [popular SQL database for developers](https://insights.stackoverflow.com/survey/2021#section-most-loved-dreaded-and-wanted-databases).
|
||||
|
||||
There are three ways of managing your database:
|
||||
|
||||
1. Nhost Database UI (recommended).
|
||||
2. Hasura Console.
|
||||
3. [Connect directly to the database.](#postgres-access)
|
||||
|
||||
## Schemas
|
||||
|
||||
Generally, you should use the `public` schema for your project. It's also ok to add custom schemas for more advanced usage.
|
||||
|
||||
The two schemas `auth` and `storage` are reserved for [Nhost Auth](/authentication) and [Nhost Storage](/storage). You're allowed to modify **permissions** and **add relationships**. However, never modify any tables or remove relationships that were added by Nhost inside the `auth` and `storage` schemas.
|
||||
|
||||
## Manage Tables
|
||||
|
||||
### Create Table
|
||||
|
||||
1. Go to **Database** in the left menu.
|
||||
2. Click **New table**.
|
||||
3. Enter a **name** for the table.
|
||||
4. Add **columns**.
|
||||
5. Select a **Primary Key** (usually the `id` column).
|
||||
6. (Optional) Select an **Identity** column. Identity is for integer columns only and is usually selected for the `id` column so the `id` is automatically incremented (1,2,3...) on new rows.
|
||||
7. (Optional) Add **Foreign Keys**.
|
||||
8. Click **Create**.
|
||||
|
||||
When a table is created it is instantly available through the [GraphQL API](/graphql).
|
||||
|
||||
Here's an example of how to create a `customers` table:
|
||||
|
||||
<Tabs groupId="nhost-vs-sql">
|
||||
<TabItem value="nhost" label="Nhost" default>
|
||||
|
||||
<video width="99%" autoPlay muted loop controls="true">
|
||||
<source src="/videos/nhost-table-create.mp4" type="video/mp4" />
|
||||
</video>
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="sql" label="SQL">
|
||||
|
||||
```sql
|
||||
CREATE TABLE "public"."customers" (
|
||||
"id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
"name" text NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### Edit Table
|
||||
|
||||
1. Go to the **Database** in the left menu
|
||||
2. Click on the **context menu** of the table you want to change and click **Edit table**.
|
||||
3. **Edit** (add, change, delete) the table's columns.
|
||||
4. Click **Save**.
|
||||
|
||||
Here's an example of how to edit a `customers` table by adding an `address` column:
|
||||
|
||||
<Tabs groupId="nhost-vs-sql">
|
||||
<TabItem value="nhost" label="Nhost" default>
|
||||
|
||||
<video width="99%" autoPlay muted loop controls="true">
|
||||
<source src="/videos/nhost-table-edit.mp4" type="video/mp4" />
|
||||
</video>
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="sql" label="SQL">
|
||||
|
||||
```sql
|
||||
ALTER TABLE "public"."customers" ADD COLUMN "address" text;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### Delete Table
|
||||
|
||||
1. Go to the **Database** in the left menu
|
||||
2. Click on the **context menu** of the table you want to delete and click **Delete table**.
|
||||
3. Click **Delete** to confirm deleting the table.
|
||||
|
||||
**Example:** Delete a `customers` table:
|
||||
|
||||
<Tabs groupId="nhost-vs-sql">
|
||||
<TabItem value="nhost" label="Nhost" default>
|
||||
|
||||
<video width="99%" autoPlay muted loop controls="true">
|
||||
<source src="/videos/nhost-table-delete.mp4" type="video/mp4" />
|
||||
</video>
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="sql" label="SQL">
|
||||
|
||||
```sql
|
||||
DROP TABLE "public"."customers";
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Postgres Access
|
||||
|
||||
It's possible to access your Postgres database directly with your favorite Postgres client.
|
||||
|
||||
Go to **Settings** in the left menu and click on **Database**. You'll find the connection string and credentials to connect to your database.
|
||||
|
||||

|
||||
|
||||
### Reset Postgres Password
|
||||
|
||||
It's possible to reset the database password under **Settings** -> **Database** -> **Reset Password**.
|
||||
|
||||
<video width="99%" autoPlay muted loop controls="true">
|
||||
<source src="/videos/nhost-database-reset-password.mp4" type="video/mp4" />
|
||||
</video>
|
||||
|
||||
## Migrations
|
||||
|
||||
To track database changes, use the [Nhost CLI](/cli) to develop locally and use our [Git integration](/platform/git) to automatically deploy database migrations live.
|
||||
|
||||
1. Develop locally using the Nhost CLI.
|
||||
2. Push changes to GitHub.
|
||||
3. Nhost automatically deploys changes.
|
||||
|
||||
Learn how to do [development with the Nhost CLI](/cli/local-development).
|
||||
|
||||
## Seed Data
|
||||
|
||||
Seed data is a way of automatically adding data to your database using SQL when a new environment is created. This is, for the moment, only applicable when you're using the [Nhost CLI](/cli) to develop locally. When you're running `nhost up` for the first time, seed data is added.
|
||||
|
||||
In the future, seed data will also be added to new preview environments.
|
||||
|
||||
Seed data should be located in `nhost/seeds/default/` and are executed in alphabetical order.
|
||||
|
||||
**Example:** Two seed scripts with countries and products.
|
||||
|
||||
```text
|
||||
nhost/seeds/default/001-countries.sql
|
||||
nhost/seeds/default/002-products.sql
|
||||
```
|
||||
|
||||
## Backups
|
||||
|
||||
Databases on the [Pro and Enterprise plans](https://nhost.io/pricing) are automatically backed up daily.
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Use lower-case names for tables. E.g. `customers` instead of `Customers`.
|
||||
- Use plural names for tables. E.g. `customers` instead of `customer`.
|
||||
- use underscore (`_`) instead of camelCase for table names. E.g. `customer_invoices` instead of `customerInvoices`.
|
||||
- use underscore (`_`) instead of camelCase for column names. E.g. `first_name` instead of `firstName`.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Learn PostgreSQL Tutorial - Full Course for Beginners (YouTube)](https://www.youtube.com/watch?v=qw--VYLpxG4).
|
||||
- Learn more about how to manage your [Postgres database in Hasura](https://hasura.io/docs/latest/graphql/core/databases/postgres/schema/index/).
|
||||
- Learn about the [GraphQL API](/graphql).
|
||||
@@ -1,84 +0,0 @@
|
||||
---
|
||||
title: 'Settings'
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
Below you can find the official schema (cue) and an example to configure your postgres database:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="schema" label="schema">
|
||||
|
||||
```cue
|
||||
#Postgres: {
|
||||
version: string | *"14.6-20230705-1"
|
||||
|
||||
// Resources for the service, optional
|
||||
resources?: #Resources & {
|
||||
replicas: 1
|
||||
}
|
||||
|
||||
// postgres settings of the same name in camelCase, optional
|
||||
settings?: {
|
||||
jit: "off" | "on" | *"on"
|
||||
maxConnections: int32 | *100
|
||||
sharedBuffers: string | *"128MB"
|
||||
effectiveCacheSize: string | *"4GB"
|
||||
maintenanceWorkMem: string | *"64MB"
|
||||
checkpointCompletionTarget: number | *0.9
|
||||
walBuffers: int32 | *-1
|
||||
defaultStatisticsTarget: int32 | *100
|
||||
randomPageCost: number | *4.0
|
||||
effectiveIOConcurrency: int32 | *1
|
||||
workMem: string | *"4MB"
|
||||
hugePages: string | *"try"
|
||||
minWalSize: string | *"80MB"
|
||||
maxWalSize: string | *"1GB"
|
||||
maxWorkerProcesses: int32 | *8
|
||||
maxParallelWorkersPerGather: int32 | *2
|
||||
maxParallelWorkers: int32 | *8
|
||||
maxParallelMaintenanceWorkers: int32 | *2
|
||||
}
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="toml" label="toml" default>
|
||||
|
||||
```toml
|
||||
[postgres]
|
||||
version = '14.6-20230925-1'
|
||||
|
||||
[postgres.resources.compute]
|
||||
cpu = 1000
|
||||
memory = 2048
|
||||
|
||||
[postgres.settings]
|
||||
jit = "off"
|
||||
maxConnections = 100
|
||||
sharedBuffers = '256MB'
|
||||
effectiveCacheSize = '768MB'
|
||||
maintenanceWorkMem = '64MB'
|
||||
checkpointCompletionTarget = 0.9
|
||||
walBuffers = -1
|
||||
defaultStatisticsTarget = 100
|
||||
randomPageCost = 1.1
|
||||
effectiveIOConcurrency = 200
|
||||
workMem = '1310kB'
|
||||
hugePages = 'off'
|
||||
minWalSize = '80MB'
|
||||
maxWalSize = '1GB'
|
||||
maxWorkerProcesses = 8
|
||||
maxParallelWorkersPerGather = 2
|
||||
maxParallelWorkers = 8
|
||||
maxParallelMaintenanceWorkers = 2
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
|
||||
:::info
|
||||
At the time of writing this document postgres settings are only supported via the [configuration file](https://nhost.io/blog/config).
|
||||
:::
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "GraphQL API",
|
||||
"position": 5
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
---
|
||||
title: 'GraphQL API'
|
||||
sidebar_position: 1
|
||||
sidebar_label: 'Overview'
|
||||
image: /img/og/graphql.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
A GraphQL API is automatically and instantly available based on the tables and columns in your [database](/database).
|
||||
|
||||
The GraphQL API has support for inserting, selecting, updating, and deleting data, which usually accounts for 80% of all API operations you need.
|
||||
|
||||
It's the [Hasura GraphQL engine](https://github.com/hasura/graphql-engine) that powers the GraphQL API which means that all documentation about [queries](https://hasura.io/docs/latest/graphql/core/databases/postgres/queries/index/), [mutations](https://hasura.io/docs/latest/graphql/core/databases/postgres/mutations/index/), and [subscriptions](https://hasura.io/docs/latest/graphql/core/databases/postgres/subscriptions/index/) from Hasura's documentation is applicable.
|
||||
|
||||
## What is GraphQL
|
||||
|
||||
GraphQL is a query language for APIs that prioritize developer experience. The GraphQL API can be used to both fetch (query) and modify (mutation) data. GraphQL is especially powerful for frontend developers who want to build products fast.
|
||||
|
||||
GraphQL has grown rapidly in popularity in the last years and has been adopted by almost all major tech companies such as Facebook, GitHub, and Stripe.
|
||||
|
||||
Building your GraphQL API is a lot of work, but with Nhost it's easy because every table and column is instantly available in your GraphQL API.
|
||||
|
||||
## Endpoint
|
||||
|
||||
The GraphQL API is available at `https://[subdomain].graphql.[region].nhost.run/v1` When using the [CLI](/cli) the GraphQL API is available at `https://local.graphql.nhost.run/v1`.
|
||||
|
||||
## GraphQL Clients for JavaScript
|
||||
|
||||
The [Nhost JavaScript client](/reference/javascript) comes with a simple [GraphQL client](/reference/javascript/graphql) that works well for the backend or simple applications.
|
||||
|
||||
When building more complex frontend applications, we recommend using a more advanced GraphQL client such as:
|
||||
|
||||
- [Apollo Client](https://www.apollographql.com/docs/react/):
|
||||
- [Nhost Apollo Client for React](/reference/react/apollo)
|
||||
- [Nhost Apollo Client for Vue](/reference/vue/apollo)
|
||||
- [URQL](https://formidable.com/open-source/urql/)
|
||||
- [React Query](https://react-query.tanstack.com/graphql)
|
||||
- [SWR](https://swr.vercel.app/docs/data-fetching#graphql)
|
||||
|
||||
## Queries
|
||||
|
||||
A query is used to fetch data from the GraphQL API.
|
||||
|
||||
:::tip
|
||||
The [Queries documentation from Hasura](https://hasura.io/docs/latest/graphql/core/databases/postgres/queries/index/) is applicable since we're using Hasura's GraphQL Engine for your project.
|
||||
:::
|
||||
|
||||
**Example:** A GraphQL query to select `title`, `body`, and `isCompleted` for every row in the `todos` table.
|
||||
|
||||
<Tabs >
|
||||
<TabItem value="request" label="Request" default>
|
||||
|
||||
```graphql
|
||||
query GetTodos {
|
||||
todos {
|
||||
title
|
||||
body
|
||||
isCompleted
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="response" label="Response">
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"todos": [
|
||||
{
|
||||
"title": "Delete Firebase account",
|
||||
"body": "Migrate to Nhost",
|
||||
"isCompleted": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
#### Filtering and sorting
|
||||
|
||||
More complex queries utilize filters, limits, sorting, and aggregation.
|
||||
|
||||
Here's an example of a more complex GraphQL query that selects all items in the `todos` table that are not completed, with the total number of comments and the last five comments:
|
||||
|
||||
<Tabs >
|
||||
<TabItem value="request" label="Request" default>
|
||||
|
||||
```graphql
|
||||
query GetTodosWithLatestComments {
|
||||
todos(where: { isCompleted: { _eq: false } }) {
|
||||
title
|
||||
body
|
||||
comments(limit: 5, order_by: { createdAt: desc }) {
|
||||
comment
|
||||
createdAt
|
||||
author
|
||||
}
|
||||
comments_aggregate {
|
||||
aggregate {
|
||||
count(columns: id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="response" label="Response">
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"todos": [
|
||||
{
|
||||
"title": "Delete Firebase account",
|
||||
"body": "Migrate to Nhost",
|
||||
"comments": [
|
||||
{
|
||||
"comment": "Let's do this",
|
||||
"created_at": "2019-10-31T08:34:25.621167+00:00",
|
||||
"author": "John"
|
||||
},
|
||||
{
|
||||
"comment": "🎉",
|
||||
"created_at": "2019-10-31T08:33:18.465623+00:00",
|
||||
"author": "Charlie"
|
||||
}
|
||||
],
|
||||
"comments_aggregate": {
|
||||
"aggregate": {
|
||||
"count": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Mutations
|
||||
|
||||
A GraphQL mutation is used to insert, upsert, update, or delete data.
|
||||
|
||||
:::tip
|
||||
The [Mutations documentation from Hasura](https://hasura.io/docs/latest/graphql/core/databases/postgres/mutations/index/) is applicable since we're using Hasura's GraphQL Engine for your project.
|
||||
:::
|
||||
|
||||
### Insert Data
|
||||
|
||||
**Example:** A GraphQL mutation to insert data:
|
||||
|
||||
<Tabs >
|
||||
<TabItem value="request" label="Request" default>
|
||||
|
||||
```graphql
|
||||
mutation InsertTodo {
|
||||
insert_todos(
|
||||
objects: [{ title: "Delete Firebase account", body: "Migrate to Nhost", isCompleted: false }]
|
||||
) {
|
||||
returning {
|
||||
id
|
||||
title
|
||||
body
|
||||
isCompleted
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="response" label="Response">
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"insert_todos": [
|
||||
{
|
||||
"id": "bf4b01ec-8eb6-451b-afac-81f5058ce852",
|
||||
"title": "Delete Firebase account",
|
||||
"body": "Migrate to Nhost",
|
||||
"isCompleted": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
#### Insert Multiple Rows
|
||||
|
||||
Use an array of objects to insert multiple rows at the same time.
|
||||
|
||||
**Example:** Insert multiple Todos at the same time:
|
||||
|
||||
```graphql title=GraphQL
|
||||
mutation InsertMultipleTodos {
|
||||
insert_todos(
|
||||
objects: [
|
||||
{ title: "Build the front end", body: "Mobile app or website first?", isCompleted: false }
|
||||
{ title: "Launch 🚀", body: "That was easy", isCompleted: false }
|
||||
]
|
||||
) {
|
||||
returning {
|
||||
id
|
||||
title
|
||||
body
|
||||
isCompleted
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Update Data
|
||||
|
||||
You can update existing data with an update mutation. You can update multiple rows at once.
|
||||
|
||||
**Example:** A GraphQL mutation to mark a atodo item as completed:
|
||||
|
||||
```graphql title=GraphQL
|
||||
mutation UpdateTodoStatus($id: uuid, $isCompleted: Boolean) {
|
||||
update_todos(_set: { isCompleted: $isCompleted }, where: { id: { _eq: $id } }) {
|
||||
returning {
|
||||
body
|
||||
isCompleted
|
||||
title
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Notice how we are using variables as the `id` and `isDone` variables, which lets us mark any todo as completed or not completed with the same mutation.
|
||||
|
||||
### Upsert Data
|
||||
|
||||
When you're not sure if a piece of data already exists, use an upsert mutation. It will either insert an object into the database if it doesn't exist or update the fields of an existing object.
|
||||
|
||||
Unlike for update mutations, you must pass all columns to an upsert mutation.
|
||||
|
||||
To convert your insert mutation to an upsert, you need to add an `on_conflict` property for the GraphQL API to know which fields it should use to find duplicates.
|
||||
|
||||
The `on_conflict` key must be a unique key in your database:
|
||||
|
||||
```graphql title=GraphQL
|
||||
mutation UpsertTodo {
|
||||
insert_todos(
|
||||
objects: { title: "Delete Firebase account", body: "...", isCompleted: false }
|
||||
on_conflict: { constraint: todos_title_key, update_columns: [title, isCompleted] }
|
||||
) {
|
||||
returning {
|
||||
id
|
||||
title
|
||||
body
|
||||
isCompleted
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This will update `body` and `done` of the todos with the title "Delete Firebase account".
|
||||
|
||||
#### Conditional upsert
|
||||
|
||||
Inserts a new object into a table, or if the primary key already exists, updates columns if the `where` condition is met.
|
||||
|
||||
For example, you may want to only update an existing todo if it is not done:
|
||||
|
||||
```graphql
|
||||
mutation UpsertTodo {
|
||||
insert_todos(
|
||||
objects: { title: "Delete Firebase account", body: "...", done: false }
|
||||
on_conflict: {
|
||||
constraint: todos_title_key
|
||||
update_columns: [body, done]
|
||||
where: { done: { _eq: false } }
|
||||
}
|
||||
) {
|
||||
returning {
|
||||
body
|
||||
done
|
||||
id
|
||||
title
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Ignore mutation on conflict
|
||||
|
||||
If `update_columns` is empty, the mutation will be ignored if the object already exists.
|
||||
|
||||
Here we have set the `title` to a unique key, to prevent multiple tasks with the same name. We want to avoid overwriting existing todos, so the update_columns array is empty:
|
||||
|
||||
```graphql
|
||||
mutation InsertTodo {
|
||||
insert_todos(
|
||||
objects: { title: "Delete Firebase account", body: "...", done: false }
|
||||
on_conflict: { constraint: todos_title_key, update_columns: [] }
|
||||
) {
|
||||
returning {
|
||||
body
|
||||
done
|
||||
id
|
||||
title
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this case, the insert mutation is ignored because a todo with the `title` `"Delete Firebase account"` already exists, and `update_columns` is empty.
|
||||
|
||||
### Delete Data
|
||||
|
||||
To delete your data, use a delete mutation. This mutation will delete all `todos` where `done` is `true`:
|
||||
|
||||
```graphql title="GraphQL mutation"
|
||||
mutation DeleteDoneTodos {
|
||||
delete_todos(where: { done: { _eq: true } }) {
|
||||
affected_rows
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you have set up foreign keys which will restrict a delete violation, you will get an error and will not be able to delete the data until all violations are solved. The simplest way to solve this is by set `On Delete Violation` to `CASCADE` when you set up a foreign key.
|
||||
|
||||
## Subscriptions
|
||||
|
||||
GraphQL subscriptions are queries that use WebSockets to keep the data up to date in your app in real-time. You only have to change `query` to `subscription` when constructing the GraphQL document:
|
||||
|
||||
```graphql title="GraphQL subscription"
|
||||
subscription GetTodos {
|
||||
todos {
|
||||
title
|
||||
body
|
||||
done
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Your data is always in sync when using subscriptions. It does not matter if the data changes through GraphQL or directly in the database. The data is always syncing in real-time using GraphQL subscriptions.
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "Remote Schemas",
|
||||
"position": 11
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
---
|
||||
title: Stripe GraphQL API
|
||||
sidebar_label: Stripe
|
||||
sidebar_position: 2
|
||||
image: /img/og/graphql.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
This package creates a Stripe GraphQL API, allowing for interaction with data at Stripe.
|
||||
|
||||
Here's an example of how to use the Stripe GraphQL API to get a list of invoices for a specific Stripe customer:
|
||||
|
||||
<Tabs >
|
||||
<TabItem value="request" label="Request" default>
|
||||
|
||||
```graphql
|
||||
query {
|
||||
stripe {
|
||||
customer(id: "cus_xxx") {
|
||||
id
|
||||
name
|
||||
invoices {
|
||||
data {
|
||||
id
|
||||
created
|
||||
paid
|
||||
hostedInvoiceUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="response" label="Response">
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"stripe": {
|
||||
"customer": {
|
||||
"id": "cus_xxx",
|
||||
"name": "joe@example.com",
|
||||
"invoices": {
|
||||
"data": [
|
||||
{
|
||||
"id": "in_1MUmwnCCF9wuB4xxxxxxxx",
|
||||
"created": 1674806769,
|
||||
"paid": true,
|
||||
"hostedInvoiceUrl": "https://invoice.stripe.com/i/acct_xxxxxxx/test_YWNjdF8xS25xV1lDQ0Y5d3VCNGZYLF9ORkhWxxxxxxxxxxxx?s=ap"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
It's recommended to add the Stripe GraphQL API as a [Remote Schema in Hasura](https://hasura.io/docs/latest/remote-schemas/index/) and connect data from your database with data in Stripe. By doing so, it's possible to request data from your database and Stripe in a single GraphQL query.
|
||||
|
||||
Here's an example of how to use the Stripe GraphQL API to get a list of invoices for a specific Stripe customer. Note that the user data is fetched from your database and the Stripe customer data is fetched from Stripe:
|
||||
|
||||
```graphql
|
||||
query {
|
||||
users {
|
||||
# User in your database
|
||||
id
|
||||
displayName
|
||||
userData {
|
||||
stripeCustomerId # Customer's Stripe Customer Id
|
||||
stripeCustomer {
|
||||
# Data from Stripe
|
||||
id
|
||||
name
|
||||
paymentMethods {
|
||||
id
|
||||
card {
|
||||
brand
|
||||
last4
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Get Started
|
||||
|
||||
Install the package:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/stripe-graphql-js
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn install @nhost/stripe-graphql-js
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="pnpm" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm add @nhost/stripe-graphql-js
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Serverless Function
|
||||
|
||||
Create a new [Serverless Function](/serverless-functions): `functions/graphql/stripe.ts`:
|
||||
|
||||
```ts
|
||||
import { createStripeGraphQLServer } from '@nhost/stripe-graphql-js'
|
||||
|
||||
const server = createStripeGraphQLServer()
|
||||
|
||||
export default server
|
||||
```
|
||||
|
||||
> You can run the Stripe GraphQL API in any Node.js environment because it's built using [GraphQL Yoga](https://github.com/dotansimha/graphql-yoga).
|
||||
|
||||
## Stripe Secret Key
|
||||
|
||||
Add `STRIPE_SECRET_KEY` as an environment variable.
|
||||
|
||||
If you're using Nhost, add `STRIPE_SECRET_KEY` to `nhost.toml` like this:
|
||||
|
||||
```
|
||||
[[ global.environment ]]
|
||||
name=STRIPE_SECRET_KEY
|
||||
value='{{ secrets.STRIPE_SECRET_KEY }}'
|
||||
```
|
||||
|
||||
And then add to your `.secrets` file:
|
||||
|
||||
```
|
||||
STRIPE_SECRET_KEY=sk_test_***
|
||||
```
|
||||
|
||||
In production set your secret with your stripe production key (`sk_live_***`) in the Nhost dashboard.
|
||||
|
||||
Learn more about [Stripe API keys](https://stripe.com/docs/keys#obtain-api-keys).
|
||||
|
||||
## Start Nhost
|
||||
|
||||
```
|
||||
nhost up
|
||||
```
|
||||
|
||||
Learn more about the [Nhost CLI](/cli).
|
||||
|
||||
## Test
|
||||
|
||||
Test the Stripe GraphQL API in the browser:
|
||||
|
||||
[https://local.functions.nhost.run/v1/graphql/stripe](https://local.functions.nhost.run/v1/graphql/stripe)
|
||||
|
||||
## Remote Schema
|
||||
|
||||
Add the Stripe GraphQL API as a Remote Schema in Hasura.
|
||||
|
||||
**URL**
|
||||
|
||||
```
|
||||
{{NHOST_FUNCTIONS_URL}}/graphql/stripe
|
||||
```
|
||||
|
||||
**Headers**
|
||||
|
||||
```
|
||||
x-nhost-webhook-secret: NHOST_WEBHOOK_SECRET (From env var)
|
||||
```
|
||||
|
||||
> The `NHOST_WEBHOOK_SECRET` is used to verify that the request is coming from Nhost. The environment variable is a [system environment variable](/platform/environment-variables#system-environment-variables) and is always available.
|
||||
|
||||

|
||||
|
||||
## Permissions
|
||||
|
||||
Here's a minimal example without any custom permissions. Only requests using the `x-hasura-admin-secret` header will work:
|
||||
|
||||
```js
|
||||
const server = createStripeGraphQLServer()
|
||||
```
|
||||
|
||||
For more granular permissions, you can pass an `isAllowed` function to the `createStripeGraphQLServer`. The `isAllowed` function takes a `stripeCustomerId` and [`context`](#context) as parameters and runs every time the GraphQL server makes a request to Stripe to get or modify data for a specific Stripe customer.
|
||||
|
||||
Here is an example of an `isAllowed` function:
|
||||
|
||||
```ts
|
||||
import { createStripeGraphQLServer } from '@nhost/stripe-graphql-js'
|
||||
|
||||
const isAllowed = (stripeCustomerId: string, context: Context) => {
|
||||
const { isAdmin, userClaims } = context
|
||||
|
||||
// allow all requests if they have a valid `x-hasura-admin-secret`
|
||||
if (isAdmin) {
|
||||
return true
|
||||
}
|
||||
|
||||
// get user id
|
||||
const userId = userClaims['x-hasura-user-id']
|
||||
|
||||
// check if the user is signed in
|
||||
if (!userId) {
|
||||
return false
|
||||
}
|
||||
|
||||
// get more user information from the database
|
||||
const { user } = await gqlSDK.getUser({
|
||||
id: userId
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return false
|
||||
}
|
||||
|
||||
// check if the user is part of a workspace with the `stripeCustomerId`
|
||||
return user.workspaceMembers.some((workspaceMember) => {
|
||||
return workspaceMember.workspace.stripeCustomerId === stripeCustomerId
|
||||
})
|
||||
}
|
||||
|
||||
const server = createStripeGraphQLServer({ isAllowed })
|
||||
|
||||
export default server
|
||||
```
|
||||
|
||||
### Context
|
||||
|
||||
The `context` object contains:
|
||||
|
||||
- `userClaims` - verified JWT claims from the user's access token.
|
||||
- `isAdmin` - `true` if the request was made using a valid `x-hasura-admin-secret` header.
|
||||
- `request` - [Fetch API Request object](https://developer.mozilla.org/en-US/docs/Web/API/Request) that represents the incoming HTTP request in platform-independent way. It can be useful for accessing headers to authenticate a user
|
||||
- `query` - the DocumentNode that was parsed from the GraphQL query string
|
||||
- `operationName` - the operation name selected from the incoming query
|
||||
- `variables` - the variables that were defined in the query
|
||||
- `extensions` - the extensions that were received from the client
|
||||
|
||||
Read more about the [default context from GraphQL Yoga](https://www.the-guild.dev/graphql/yoga-server/docs/features/context#default-context).
|
||||
|
||||
## Source Code
|
||||
|
||||
The source code is available on [GitHub](https://github.com/nhost/nhost/tree/main/integrations/stripe-graphql-js).
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
title: 'Introduction to Nhost'
|
||||
sidebar_label: Introduction
|
||||
image: /img/og/introduction-to-nhost.png
|
||||
---
|
||||
|
||||
Nhost is the open source GraphQL backend (Firebase Alternative) and a development platform. Nhost is doing for the backend, what [Netlify](https://netlify.com/) and [Vercel](https://vercel.com/) are doing for the frontend.
|
||||
|
||||
We provide a modern backend with the general building blocks required to build fantastic digital products.
|
||||
|
||||
We make it easy to build and deploy this backend using our platform which takes care of configuration, security, and performance. Things just work and scale automatically so you can focus on your product and your business.
|
||||
|
||||
## Quickstart
|
||||
|
||||
Get started quickly by following one of our quickstart guides:
|
||||
|
||||
- [Next.js](/quickstarts/nextjs)
|
||||
- [React](/quickstarts/react)
|
||||
- [RedwoodJS](/quickstarts/redwoodjs)
|
||||
- [Vue](/quickstarts/vue)
|
||||
|
||||
## Products and Features
|
||||
|
||||
Learn more about the product and features of Nhost.
|
||||
|
||||
- [Database](/database)
|
||||
- [GraphQL API](/graphql)
|
||||
- [Authentication](/authentication)
|
||||
- [Storage](/storage)
|
||||
- [Serverless Functions](/serverless-functions)
|
||||
- [Run](/run)
|
||||
|
||||
## Architecture
|
||||
|
||||
Nhost is a Backend-as-a-Service built with open source tools to provide developers the general building blocks required to build fantastic digital apps and products.
|
||||
|
||||
Here's a diagram of the Nhost stack on a high level:
|
||||
|
||||

|
||||
|
||||
As you see in the image above, Nhost provides endpoints for:
|
||||
|
||||
- GraphQL API (`/graphql`)
|
||||
- Authentication (`/auth`)
|
||||
- Storage (`/storage`)
|
||||
- Functions (`/functions`)
|
||||
|
||||
Data is stored in Postgres and files are stored in S3.
|
||||
|
||||
## Open Source
|
||||
|
||||
The open source tools used for the full Nhost stack are:
|
||||
|
||||
- Database: [Postgres](https://www.postgresql.org/)
|
||||
- GraphQL API: [Hasura](https://github.com/hasura/graphql-engine)
|
||||
- Authentication: [Hasura Auth](https://github.com/nhost/hasura-auth)
|
||||
- Storage: [Hasura Storage](https://github.com/nhost/hasura-storage)
|
||||
- Functions: [Node.js](https://nodejs.org/en/)
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
title: 'Introduction to Nhost'
|
||||
sidebar_label: Introduction
|
||||
image: /img/og/introduction-to-nhost.png
|
||||
---
|
||||
|
||||
Nhost is the open source GraphQL backend (Firebase Alternative) and a development platform. Nhost is doing for the backend, what [Netlify](https://netlify.com/) and [Vercel](https://vercel.com/) are doing for the frontend.
|
||||
|
||||
We provide a modern backend with the general building blocks required to build fantastic digital products.
|
||||
|
||||
We make it easy to build and deploy this backend using our platform which takes care of configuration, security, and performance. Things just work and scale automatically so you can focus on your product and your business.
|
||||
|
||||
## Quickstart
|
||||
|
||||
Get started quickly by following one of our quickstart guides:
|
||||
|
||||
- [Next.js](/quickstarts/nextjs)
|
||||
- [React](/quickstarts/react)
|
||||
- [RedwoodJS](/quickstarts/redwoodjs)
|
||||
- [Vue](/quickstarts/vue)
|
||||
|
||||
## Products and Features
|
||||
|
||||
Learn more about the product and features of Nhost.
|
||||
|
||||
- [Database](/database)
|
||||
- [GraphQL API](/graphql)
|
||||
- [Authentication](/authentication)
|
||||
- [Storage](/storage)
|
||||
- [Serverless Functions](/serverless-functions)
|
||||
|
||||
## Architecture
|
||||
|
||||
Nhost is a Backend-as-a-Service built with open source tools to provide developers the general building blocks required to build fantastic digital apps and products.
|
||||
|
||||
Here's a diagram of the Nhost stack on a high level:
|
||||
|
||||

|
||||
|
||||
As you see in the image above, Nhost provides endpoints for:
|
||||
|
||||
- GraphQL API (`/graphql`)
|
||||
- Authentication (`/auth`)
|
||||
- Storage (`/storage`)
|
||||
- Functions (`/functions`)
|
||||
|
||||
Data is stored in Postgres and files are stored in S3.
|
||||
|
||||
## Open Source
|
||||
|
||||
The open source tools used for the full Nhost stack are:
|
||||
|
||||
- Database: [Postgres](https://www.postgresql.org/)
|
||||
- GraphQL API: [Hasura](https://github.com/hasura/graphql-engine)
|
||||
- Authentication: [Hasura Auth](https://github.com/nhost/hasura-auth)
|
||||
- Storage: [Hasura Storage](https://github.com/nhost/hasura-storage)
|
||||
- Functions: [Node.js](https://nodejs.org/en/)
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "Platform",
|
||||
"position": 10
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: 'Compute Resources'
|
||||
sidebar_position: 1
|
||||
image: /img/og/platform/compute-resources.png
|
||||
---
|
||||
|
||||
Compute resources are the fundamental units that represent the processing power and memory available to your Nhost projects. The primary compute resources are vCPU and RAM. This documentation outlines the key aspects of compute resources in the context of the Nhost Cloud Platform.
|
||||
|
||||
|
||||
### Shared vs Dedicated Compute
|
||||
|
||||
Free Projects are given a total of 2 shared vCPUs and 1 GiB of RAM:
|
||||
|
||||
- Postgres: 0.5 vCPU / 256 MiB
|
||||
- Hasura GraphQL: 0.5 vCPU / 384 MiB
|
||||
- Auth: 0.5 vCPU / 256 MiB
|
||||
- Storage: 0.5 vCPU / 128 MiB
|
||||
|
||||
Pro Projects are given a total of 2 shared vCPUs and 2 GiB of RAM:
|
||||
|
||||
- Postgres: 0.5 vCPU / 512 MiB
|
||||
- Hasura GraphQL: 0.5 vCPU / 768 MiB
|
||||
- Auth: 0.5 vCPU / 384 MiB
|
||||
- Storage: 0.5 vCPU / 384 MiB
|
||||
|
||||
This is fine if your apps mostly run at low to medium load, occasionally burst for brief periods of time, and can tolerate drops in performance. It is important to understand that the availability of CPU time is not guaranteed.
|
||||
|
||||
### Dedicated Compute
|
||||
|
||||
On the other hand, for high production workloads where latency is important, or variable performance is not at all tolerable, you should consider configuring your project to use dedicated compute resources.
|
||||
With dedicated compute, resources are guaranteed for your project so you don't have to contend for them.
|
||||
|
||||
In addition to the resources fully dedicated to the project, apps are allowed to burst if demand requires it and resources are available. If properly sized, dedicated resources should guarantee the performance of your application while allowing for occassional burts.
|
||||
|
||||
To configure dedicated compute to your projects, all you have to do is navigate to the project's settings, and click on "Compute Resources" (see image below). There you will be able to choose the total amount of resources you want to dedicate, and spread those resources amongst all services.
|
||||
|
||||
|
||||

|
||||
|
||||
To further improve availability and fault tolerance, you can also leverage Service Replicas. To learn more, check out the documentation for [Service Replicas](https://docs.nhost.io/platform/service-replicas).
|
||||
@@ -1,89 +0,0 @@
|
||||
---
|
||||
title: 'Environment Variables'
|
||||
sidebar_position: 2
|
||||
image: /img/og/platform/environment-variables.png
|
||||
---
|
||||
|
||||
Environment Variables are key-value pairs configured outside your source code. They are used to store environment-specific values such as API keys.
|
||||
|
||||
Environment Variables are available for:
|
||||
|
||||
- [Hasura GraphQL Engine](/graphql)
|
||||
- [Serverless Functions](/serverless-functions)
|
||||
|
||||
When an Environment Variable has updated the changes happen immediately for Hasura GraphQL Engine. For Serverless Functions, a new deployment via [Git](/platform/git) is required.
|
||||
|
||||
## Custom Environment Variables
|
||||
|
||||
You can manage your project's Environment Variables in the Nhost Dashboard or by using the configuration file.
|
||||
|
||||
### Dashboard
|
||||
|
||||

|
||||
|
||||
Environment Variables can be managed in the Nhost Dashboard under **Settings** → **Environment Variables**.
|
||||
|
||||
### Configuration File
|
||||
|
||||
Environment Variables can also be managed by adding new `[[global.environment]]` sections to the `nhost.toml` file.
|
||||
|
||||
```toml
|
||||
[global]
|
||||
[[global.environment]]
|
||||
name = 'MY_ENV_VAR'
|
||||
value = '<first-value>'
|
||||
|
||||
[[global.environment]]
|
||||
name = 'MY_OTHER_ENV_VAR'
|
||||
value = '<second-value>'
|
||||
|
||||
# ... omitted for brevity
|
||||
```
|
||||
|
||||
These environment variables will also be available on the Nhost Dashboard after committing and pushing the changes to your Git repository.
|
||||
|
||||
## System Environment Variables
|
||||
|
||||
System environment variables are automatically generated from the configuration file and your project's subdomain and region.
|
||||
|
||||
The following system environment variables are available:
|
||||
|
||||
- `NHOST_ADMIN_SECRET`
|
||||
- `NHOST_WEBHOOK_SECRET`
|
||||
- ~~`NHOST_BACKEND_URL`~~ ([deprecated](https://github.com/nhost/nhost/discussions/1319))
|
||||
- `NHOST_SUBDOMAIN`
|
||||
- `NHOST_REGION`
|
||||
- `NHOST_HASURA_URL`
|
||||
- `NHOST_AUTH_URL`
|
||||
- `NHOST_GRAPHQL_URL`
|
||||
- `NHOST_STORAGE_URL`
|
||||
- `NHOST_FUNCTIONS_URL`
|
||||
- `NHOST_JWT_SECRET`
|
||||
|
||||
`NHOST_ADMIN_SECRET`, `NHOST_WEBHOOK_SECRET` and `NHOST_JWT_SECRET` are populated with values from the configuration file. The rest of the system environment variables are populated with values from your project's subdomain and region.
|
||||
|
||||
**Example values**:
|
||||
|
||||
```text
|
||||
NHOST_ADMIN_SECRET=e7w36ag287qn5qry795f6ymm57qgvqup
|
||||
|
||||
NHOST_WEBHOOK_SECRET=ns3sfjgdw4y6zeqthwnnw347dzh8wyj4
|
||||
|
||||
NHOST_BACKEND_URL=https://abc123abc.nhost.run
|
||||
|
||||
NHOST_SUBDOMAIN=abv123abc
|
||||
|
||||
NHOST_REGION=eu-central-1
|
||||
|
||||
NHOST_HASURA_URL=https://abc123abc.hasura.eu-central-1.nhost.run/console
|
||||
|
||||
NHOST_AUTH_URL=https://abc123abc.auth.eu-central-1.nhost.run/v1
|
||||
|
||||
NHOST_GRAPHQL_URL=https://abc123abc.graphql.eu-central-1.nhost.run/v1
|
||||
|
||||
NHOST_STORAGE_URL=https://abc123abc.storage.eu-central-1.nhost.run/v1
|
||||
|
||||
NHOST_FUNCTIONS_URL=https://abc123abc.functions.eu-central-1.nhost.run/v1
|
||||
|
||||
NHOST_JWT_SECRET={"type": "HS256", "key": "vumpbe2w2mgaqj5yqfp7dvxu6kywtvsgb68ejpdaqxerea8jwrsszdp2dhkjxsh4df69pzm3ja6ukedx8ja43zdt6q9kgbgg2w9vh2sedeppukud9a2qzy29v3afdn7m"}
|
||||
```
|
||||
@@ -1,54 +0,0 @@
|
||||
---
|
||||
title: 'Git'
|
||||
sidebar_position: 2
|
||||
image: /img/og/platform/github-integration.png
|
||||
---
|
||||
|
||||
Nhost allows you to automatically deploy your Nhost project when you do changes to your Git repository.
|
||||
|
||||
## Supported Git Providers
|
||||
|
||||
- GitHub
|
||||
|
||||
Support GitLab, BitBucket, and other Git providers are on our roadmap.
|
||||
|
||||
## Deployment
|
||||
|
||||
The following things are deployed:
|
||||
|
||||
- Database migrations
|
||||
- Hasura metadata
|
||||
- Serverless Functions
|
||||
- Email Templates
|
||||
|
||||
:::caution
|
||||
Settings in `nhost/config.yaml` are **not** deployed. That means you need to manually sync settings between local and remote environments between the CLI and Nhost Cloud.
|
||||
:::
|
||||
|
||||
## Using GitHub
|
||||
|
||||
1. From your Nhost project, click **Connect to Github**.
|
||||
|
||||

|
||||
|
||||
2. **Install the Nhost project** on your Github account.
|
||||
|
||||

|
||||
|
||||
3. **Connect** your Github repository.
|
||||
|
||||

|
||||
|
||||
## Deployment Branch
|
||||
|
||||
Nhost only deploys changes from the **Deployment Branch**. By default, your deployment branch matches the default branch (usually `main`).
|
||||
|
||||
You can change the Deployment Branch on the **Git** page in the **Settings** section.
|
||||
|
||||
It's possible to have multiple Nhost projects connected to the same Git repository and use different Deployment Branches (e.g., `main` and `staging`). Learn more about [multiple environments](/platform/multiple-environments).
|
||||
|
||||
## Base Directory
|
||||
|
||||
If your Nhost project is not located at the root of your Git repository, which is typically the case when using a monorepo, it's possible to set a custom Base Directory. The Base Directory is where the `nhost/` directory is located. In other words, the Base Directory is the **parent directory** of the `nhost/` directory.
|
||||
|
||||
You can change the Base Directory on the **Git** page in the **Settings** section.
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
title: 'Metrics (beta)'
|
||||
sidebar_position: 1
|
||||
image: /img/og/platform/metrics.png
|
||||
---
|
||||
|
||||
Metrics provide insights into your Nhost projects by integrating a managed Grafana instance tailored to them. This feature is available on the Pro plan and allows you to analyze your project's performance, identify potential bottlenecks, and optimize your application.
|
||||
|
||||
### Available Dashboards
|
||||
|
||||
Nhost Metrics includes a few pre-configured dashboards with the following metrics:
|
||||
|
||||
- vCPU/memory usage by Service replica for all services
|
||||
- Throttling time / percentage
|
||||
- Postgres volume usage
|
||||
- Networking
|
||||
- [Functions](/serverless-functions) metrics like calls, response times, errors, etc.
|
||||
|
||||

|
||||
|
||||
### Accessing Metrics
|
||||
|
||||
Metrics can be found in your project's dashboard.
|
||||
|
||||

|
||||
|
||||
### Limitations (Beta)
|
||||
|
||||
Please note that while Metrics is in beta, its functionality and pricing might change.
|
||||
|
||||
- Users cannot save or use custom dashboards in the current beta version.
|
||||
- Additional categories of metrics like application and database metrics will be added in future updates.
|
||||
- Future updates will centralize logs using Loki and integrate alerts directly into the Grafana dashboard.
|
||||
|
||||
Using Nhost Metrics allows you to identify bottlenecks in your applications, which you can then fix by leveraging [Compute Resources](https://docs.nhost.io/platform/compute) and [Service Replicas](https://docs.nhost.io/platform/service-replicas) to address these performance issues.
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
title: 'Multiple Environments'
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
Here's a guide on how to use Nhost with multiple environments and how to set up a workflow around them.
|
||||
|
||||
For this example, we'll set up one **production environment** and one **staging environment**.
|
||||
|
||||
## Git
|
||||
|
||||
Create a new Git repo and use the [CLI](/cli) and the `nhost init` command to initialize a new project.
|
||||
|
||||
Also, create a new branch called `staging`.
|
||||
|
||||
You should now have a Git repo with a `main` branch and a `staging` branch.
|
||||
|
||||
## Nhost Cloud
|
||||
|
||||
To have two environments, we need to create two projects on Nhost Cloud.
|
||||
|
||||
Both projects must be connected to the **same** [Git](/platform/git) repo, but using **different** [deployment branches](/platform/git#deployment-branch).
|
||||
|
||||
Set your production project to use the `main` branch as the Deployment Branch and your staging project to use the `staging` branch as the Deployment Branch. This way, the production project will only deploy new changes to the `main` branch and the staging project will only deploy new changes to the `staging` branch.
|
||||
|
||||
## Development
|
||||
|
||||
### Local
|
||||
|
||||
Now, use the CLI to do [local development](/cli/local-development). And use a specific feature branch while doing development.
|
||||
|
||||
### Staging
|
||||
|
||||
Once you're ready to test your changes to staging, create a pull request from your feature branch to the `staging` branch. Then, merge the pull request to `staging`.
|
||||
|
||||
This will automatically trigger a new deployment to the staging project on the Nhost platform.
|
||||
|
||||
### Production
|
||||
|
||||
Once you've tested your changes in the staging environment, you can create a new pull request from the `staging` branch to the `main` branch. Then, merge the pull request to `main`.
|
||||
|
||||
This will automatically trigger a new deployment to the production project on the Nhost platform.
|
||||
|
||||
## Configuration Overlays
|
||||
|
||||
While Nhost uses a single file to deploy all of the environments connected to the same repository and branch, overlays allow you to accommodate for minor differences in those environments by allowing you to define rules to modify the base configuration. For details on overlays head to [Configuration Overlays](/cli/overlays)
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
Now you have two environments, one for staging and one for production. You can use this workflow to do local development, and test your changes in a staging environment before deploying them to production.
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
title: 'Service Replicas'
|
||||
sidebar_position: 1
|
||||
image: /img/og/platform/service-replicas.png
|
||||
---
|
||||
|
||||
Service Replicas is a feature that allows you to create multiple replicas of your services, enhancing availability and fault tolerance for your Nhost apps. By distributing user requests among replicas, your apps can handle more traffic and provide a better user experience. This documentation touches on the key aspects of Service Replicas in the context of the Nhost Cloud Platform.
|
||||
|
||||

|
||||
|
||||
To read the announcement, check out our [blog post](https://nhost.io/blog/service-replicas).
|
||||
|
||||
### Supported Services
|
||||
|
||||
Replicas can be configured for the following services:
|
||||
|
||||
- Hasura
|
||||
- Auth
|
||||
- Storage
|
||||
|
||||
Currently, we don't support replicas for Postgres.
|
||||
|
||||
### Configuring Service Replicas
|
||||
|
||||
To configure Service Replicas for your project, follow these steps:
|
||||
|
||||
1. Navigate to your project's settings in the Nhost Dashboard.
|
||||
2. Click on "Compute Resources".
|
||||
3. Locate the "Replicas" slider for each service (Hasura, Auth, and Storage).
|
||||
4. Adjust the number of replicas for each service as needed.
|
||||
5. Save your changes.
|
||||
|
||||
Please note that when setting multiple replicas for a service, the 1:2 ratio between CPU and RAM for that service has to be respected. With only one replica, this ratio does not need to be respected at the service level.
|
||||
|
||||
### Benefits
|
||||
|
||||
- Improved fault tolerance: Multiple replicas ensure that if one instance crashes duo to an unexpected issue, the other replicas can continue to serve user requests.
|
||||
- Improved availability: Distributing user requests among multiple replicas allows your apps to handle more traffic and maintain a high level of performance.
|
||||
- Load balancing: Distributing workloads evenly among replicas to prevent bottlenecks and ensure smooth performance during peak times.
|
||||
|
||||
### Pricing
|
||||
|
||||
Pricing is based on the size of each replica and the total number of replicas you have configured for each service:
|
||||
|
||||
- If you allocate 1 vCPU and 2 GiB of RAM to the auth service, for example, the cost for a single replica is $50.
|
||||
- If you configure 3 replicas for auth, the total cost for all replicas would be $150 (3 replicas x $50 per replica).
|
||||
|
||||
Please note that Service Replicas is available only for projects on the Pro plan or higher.
|
||||
|
||||
### Caveats
|
||||
|
||||
- Postgres replication: As mentioned earlier, we do not have support for multiple replicas of Postgres. This feature may be added in the future.
|
||||
- Resource ratio: When configuring multiple replicas for a service, you must adhere to the 1:2 ratio between CPU and RAM for that service.
|
||||
|
||||

|
||||
|
||||
For more information on compute resources and scaling your apps, refer to our documentation on [Compute Resources](https://docs.nhost.io/platform/compute).
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"label": "Quickstarts",
|
||||
"position": 3,
|
||||
"collapsed": false
|
||||
}
|
||||
@@ -1,707 +0,0 @@
|
||||
---
|
||||
title: 'Quickstart: Next.js'
|
||||
sidebar_label: Next.js
|
||||
sidebar_position: 2
|
||||
image: /img/og/quickstart-nextjs.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
# Quickstart: Next.js
|
||||
|
||||
## Introduction
|
||||
|
||||
This quickstart provides the steps you need to build a Next.js app
|
||||
powered by Nhost for the backend. It includes:
|
||||
|
||||
- Database: [PostgreSQL](https://www.postgresql.org/)
|
||||
- Instant GraphQL API: [Hasura](https://hasura.io/)
|
||||
- Authentication: [Hasura Auth](https://github.com/nhost/hasura-auth/)
|
||||
- Storage: [Hasura Storage](https://hub.docker.com/r/nhost/hasura-storage)
|
||||
|
||||
By the end of this guide, you'll have a full-stack app that allows users to sign
|
||||
in to access a protected dashboard and update their profile information.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before getting started, let's make sure that your development environment is
|
||||
ready.
|
||||
|
||||
You'll need **Node.js** version 12 or later: [install it from here](https://nodejs.org/en/).
|
||||
|
||||
## Project setup
|
||||
|
||||
### Create a new Nhost app
|
||||
|
||||
import CreateApp from '@site/src/components/create-nhost-project.mdx'
|
||||
|
||||
<CreateApp />
|
||||
|
||||
:::info
|
||||
You can also connect your Nhost project to a Git repository at GitHub. When you do this, any updates you push to your code will automatically be deployed. [Learn more](/platform/git)
|
||||
:::
|
||||
|
||||
## Initialize the app
|
||||
|
||||
### Create a Next.js app
|
||||
|
||||
The simplest way to create a new Next.js application is by using the tool called
|
||||
`create-next-app`, which bootstraps a Next.js app for you without the hassle of
|
||||
configuring everything yourself.
|
||||
|
||||
So, open your terminal, and run the following command:
|
||||
|
||||
```bash
|
||||
npx create-next-app my-nhost-app --example "https://github.com/nhost/quickstart-nextjs"
|
||||
```
|
||||
|
||||
:::info
|
||||
This command uses an [existing template](https://github.com/nhost/quickstart-nextjs), through the `--example` flag, which already contains the React components and pages we'll use for this guide.
|
||||
:::
|
||||
|
||||
You can now `cd` into your project directory:
|
||||
|
||||
```bash
|
||||
cd my-nhost-app
|
||||
```
|
||||
|
||||
And run the development server with the following command:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn dev
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
If everything is working fine, your Next.js development server should be running
|
||||
on port 3000. Open [http://localhost:3000](http://localhost:3000) from your
|
||||
browser to check this out.
|
||||
|
||||
### Configure Nhost with Next.js
|
||||
|
||||
To work with Nhost from within our Next.js app, we'll use the
|
||||
[Next.js SDK](https://github.com/nhost/nhost/tree/main/packages/nextjs) provided
|
||||
by Nhost. It's a wrapper around the
|
||||
[Nhost React SDK](https://github.com/nhost/nhost/tree/main/packages/react) which
|
||||
gives us a way to interact with our Nhost backend using React hooks.
|
||||
|
||||
You can install the Nhost Next.js SDK with:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/nextjs graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn add @nhost/nextjs graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Next, open your `_app.js` file as we'll now configure Nhost inside our app.
|
||||
|
||||
The Nhost Next.js SDK comes with a React provider named `NhostProvider` that
|
||||
makes the authentication state and all the provided React hooks available in our
|
||||
application.
|
||||
|
||||
Use the following code to instantiate a new Nhost client and link it to your
|
||||
Nhost backend:
|
||||
|
||||
```jsx title="pages/_app.js"
|
||||
import { UserProvider } from '../UserProvider';
|
||||
// highlight-start
|
||||
import { NhostProvider, NhostClient } from '@nhost/nextjs';
|
||||
// highlight-end
|
||||
|
||||
// highlight-start
|
||||
const nhost = new NhostClient({
|
||||
subdomain: process.env.NEXT_PUBLIC_NHOST_SUBDOMAIN || '',
|
||||
region: process.env.NEXT_PUBLIC_NHOST_REGION || ''
|
||||
});
|
||||
// highlight-end
|
||||
|
||||
function MyApp({ Component, pageProps }) {
|
||||
return (
|
||||
{/* highlight-next-line */}
|
||||
<NhostProvider nhost={nhost} initial={pageProps.nhostSession}>
|
||||
<UserProvider>
|
||||
{/* ... */}
|
||||
</UserProvider>
|
||||
{/* highlight-next-line */}
|
||||
</NhostProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Finally, store the environment variables for `subdomain` and `region` in `.env.development`:
|
||||
|
||||
```yaml title=".env.development"
|
||||
NEXT_PUBLIC_NHOST_SUBDOMAIN=[subdomain]
|
||||
NEXT_PUBLIC_NHOST_REGION=[region]
|
||||
```
|
||||
|
||||
You find your Nhost project's `subdomain` and `region` in the [project overview](https://app.nhost.io):
|
||||
|
||||

|
||||
|
||||
:::caution
|
||||
Don't forget to restart your Next.js server after saving your `.env.development`
|
||||
file to load your new environment variable.
|
||||
:::
|
||||
|
||||
:::info Nhost CLI
|
||||
Do you use the Nhost CLI? Learn how to set `subdomain` and `region` in the [CLI documentation](/cli#subdomain-and-region).
|
||||
:::
|
||||
|
||||
## Build the app
|
||||
|
||||
### Add authentication
|
||||
|
||||
#### 1. Sign-up
|
||||
|
||||
The next step is to allow our users to authenticate into our application.
|
||||
Let's start with implementing the sign-up process.
|
||||
|
||||
For that, we'll use the `useSignUpEmailPassword` hook provided by the Nhost
|
||||
Next.js SDK within our `SignUp` component.
|
||||
|
||||
So, open up the corresponding file from your project, and use the following
|
||||
code:
|
||||
|
||||
```jsx title="components/SignUp.js"
|
||||
import styles from '../styles/components/SignUp.module.css'
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/router'
|
||||
import { useSignUpEmailPassword } from '@nhost/nextjs'
|
||||
import Link from 'next/link'
|
||||
import Image from 'next/image'
|
||||
import Input from './Input'
|
||||
import Spinner from './Spinner'
|
||||
|
||||
const SignUp = () => {
|
||||
const [firstName, setFirstName] = useState('')
|
||||
const [lastName, setLastName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const { signUpEmailPassword, isLoading, isSuccess, needsEmailVerification, isError, error } =
|
||||
useSignUpEmailPassword()
|
||||
|
||||
const handleOnSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
await signUpEmailPassword(email, password, {
|
||||
displayName: `${firstName} ${lastName}`.trim(),
|
||||
metadata: {
|
||||
firstName,
|
||||
lastName
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (isSuccess) {
|
||||
router.push('/')
|
||||
return null
|
||||
}
|
||||
|
||||
const disableForm = isLoading || needsEmailVerification
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles['logo-wrapper']}>
|
||||
<Image src="/logo.svg" alt="logo" layout="fill" objectFit="contain" />
|
||||
</div>
|
||||
|
||||
{needsEmailVerification ? (
|
||||
<p className={styles['verification-text']}>
|
||||
Please check your mailbox and follow the verification link to verify your email.
|
||||
</p>
|
||||
) : (
|
||||
<form onSubmit={handleOnSubmit} className={styles.form}>
|
||||
<div className={styles['input-group']}>
|
||||
<Input
|
||||
label="First name"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
label="Last name"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="email"
|
||||
label="Email address"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
type="password"
|
||||
label="Create password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
|
||||
<button type="submit" disabled={disableForm} className={styles.button}>
|
||||
{isLoading ? <Spinner size="sm" /> : 'Create account'}
|
||||
</button>
|
||||
|
||||
{isError ? <p className={styles['error-text']}>{error?.message}</p> : null}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className={styles.text}>
|
||||
Already have an account?{' '}
|
||||
<Link href="/sign-in">
|
||||
<a className={styles.link}>Sign in</a>
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SignUp
|
||||
```
|
||||
|
||||
By default, the user must verify his email address before fully signing up. You can change this setting from your Nhost dashboard.
|
||||
|
||||
#### 2. Sign-in
|
||||
|
||||
Now that new users can sign up for our application, let's see how to allow
|
||||
existing users to sign in with email and password.
|
||||
|
||||
For that, we will use the Nhost hook named `useSignInEmailPassword` inside our
|
||||
`SignIn` component the same way we did with our `SignUp` component. So, here's
|
||||
what your component should look like after applying the changes for the sign-in
|
||||
logic:
|
||||
|
||||
```jsx title="components/SignIn.js"
|
||||
import styles from '../styles/components/SignIn.module.css'
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/router'
|
||||
import { useSignInEmailPassword } from '@nhost/nextjs'
|
||||
import Link from 'next/link'
|
||||
import Image from 'next/image'
|
||||
import Input from './Input'
|
||||
import Spinner from './Spinner'
|
||||
|
||||
const SignIn = () => {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const { signInEmailPassword, isLoading, isSuccess, needsEmailVerification, isError, error } =
|
||||
useSignInEmailPassword()
|
||||
|
||||
const handleOnSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
await signInEmailPassword(email, password)
|
||||
}
|
||||
|
||||
if (isSuccess) {
|
||||
router.push('/')
|
||||
return null
|
||||
}
|
||||
|
||||
const disableForm = isLoading || needsEmailVerification
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles['logo-wrapper']}>
|
||||
<Image src="/logo.svg" alt="logo" layout="fill" objectFit="contain" />
|
||||
</div>
|
||||
|
||||
{needsEmailVerification ? (
|
||||
<p className={styles['verification-text']}>
|
||||
Please check your mailbox and follow the verification link to verify your email.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<form onSubmit={handleOnSubmit} className={styles.form}>
|
||||
<Input
|
||||
type="email"
|
||||
label="Email address"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
type="password"
|
||||
label="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
|
||||
<button type="submit" disabled={disableForm} className={styles.button}>
|
||||
{isLoading ? <Spinner size="sm" /> : 'Sign in'}
|
||||
</button>
|
||||
|
||||
{isError ? <p className={styles['error-text']}>{error?.message}</p> : null}
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className={styles.text}>
|
||||
No account yet?{' '}
|
||||
<Link href="/sign-up">
|
||||
<a className={styles.link}>Sign up</a>
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SignIn
|
||||
```
|
||||
|
||||
#### 3. Sign-out
|
||||
|
||||
Finally, to allow the users to sign out from the app, we can use the Nhost
|
||||
`useSignOut` hook:
|
||||
|
||||
```jsx title="components/Layout.js"
|
||||
import { useSignOut } from '@nhost/nextjs'
|
||||
|
||||
const Layout = ({ children = null }) => {
|
||||
const { signOut } = useSignOut()
|
||||
|
||||
const menuItems = [
|
||||
//..
|
||||
{
|
||||
label: 'Logout',
|
||||
onClick: signOut,
|
||||
icon: LogoutIcon
|
||||
}
|
||||
]
|
||||
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
### Protect routes
|
||||
|
||||
Now that we have implemented authentication, we can easily decide who can access
|
||||
certain parts of our application.
|
||||
|
||||
In our case, we'll only allow authenticated users to have access to the `/` and
|
||||
`/profile` routes. All the other users should be redirected to the `/sign-in`
|
||||
page if they try to access those routes.
|
||||
|
||||
To do so, we can check the authentication status of the current user using the
|
||||
Nhost SDK by creating a
|
||||
[high-order component](https://reactjs.org/docs/higher-order-components.html):
|
||||
|
||||
```jsx title="withAuth.js"
|
||||
import styles from './styles/pages/ProtectedRoute.module.css'
|
||||
import { useRouter } from 'next/router'
|
||||
import { useAuthenticationStatus } from '@nhost/nextjs'
|
||||
import Spinner from './components/Spinner'
|
||||
|
||||
export default function withAuth(Component) {
|
||||
return function AuthProtected(props) {
|
||||
const router = useRouter()
|
||||
const { isLoading, isAuthenticated } = useAuthenticationStatus()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<Spinner />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
router.push('/sign-in')
|
||||
return null
|
||||
}
|
||||
|
||||
return <Component {...props} />
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then, wrap our Next.js pages, `index.js` and `profile.js`, with it:
|
||||
|
||||
<Tabs
|
||||
defaultValue="index"
|
||||
values={[
|
||||
{label: 'pages/index.js', value: 'index'},
|
||||
{label: 'pages/profile.js', value: 'profile'},
|
||||
]}>
|
||||
<TabItem value="index">
|
||||
|
||||
```js
|
||||
import withAuth from '../withAuth'
|
||||
|
||||
const Home = () => {
|
||||
//...
|
||||
}
|
||||
|
||||
export default withAuth(Home)
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="profile">
|
||||
|
||||
```js
|
||||
import withAuth from '../withAuth'
|
||||
|
||||
const Profile = () => {
|
||||
//...
|
||||
}
|
||||
|
||||
export default withAuth(Profile)
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### Retrieve user data
|
||||
|
||||
Finally, let's display the information of the authenticated user throughout his
|
||||
dashboard to make the app more personalized.
|
||||
|
||||
Getting the current authenticated user data is quite easy. We
|
||||
can use the `useUserData` hook provided by Nhost to do it.
|
||||
|
||||
So, open the `UserProvider.js` file and use this hook like so:
|
||||
|
||||
```js
|
||||
import React, { useContext } from 'react'
|
||||
// highlight-next-line
|
||||
import { useUserData } from '@nhost/nextjs'
|
||||
|
||||
const UserContext = React.createContext(null)
|
||||
|
||||
export function UserProvider({ children = null }) {
|
||||
// highlight-next-line
|
||||
const user = useUserData()
|
||||
return <UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
|
||||
}
|
||||
|
||||
export function useUserContext() {
|
||||
return useContext(UserContext)
|
||||
}
|
||||
```
|
||||
|
||||
That's it! The JSX code for rendering the user data (email, display name, etc.)
|
||||
is already included in your components as part of the example repository you've
|
||||
bootstrapped at the beginning of this guide.
|
||||
|
||||
### Update user data
|
||||
|
||||
Nhost provides a GraphQL API through Hasura so that we can query and mutate our
|
||||
data instantly.
|
||||
|
||||
In this tutorial, we'll use the
|
||||
[Apollo GraphQL client](https://www.apollographql.com/) for interacting with
|
||||
this GraphQL API.
|
||||
|
||||
So, start by installing the following dependencies:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/react-apollo @apollo/client
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn add @nhost/react-apollo @apollo/client
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Then, add the `NhostApolloProvider` from `@nhost/react-apollo` into your
|
||||
`_app_.js` file.
|
||||
|
||||
```jsx title="pages/_app.js"
|
||||
import { NhostApolloProvider } from '@nhost/react-apollo'
|
||||
|
||||
function MyApp({ Component, pageProps }) {
|
||||
return (
|
||||
<NhostProvider nhost={nhost} initial={pageProps.nhostSession}>
|
||||
<NhostApolloProvider nhost={nhost}>{/* ... */}</NhostApolloProvider>
|
||||
</NhostProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
From there, we can construct our GraphQL query and use the Apollo `useMutation`
|
||||
hook to execute that query when the user submits the form from the profile page:
|
||||
|
||||
```js title="pages/profile.js"
|
||||
import { gql, useMutation } from '@apollo/client'
|
||||
import { toast } from 'react-hot-toast'
|
||||
|
||||
const UPDATE_USER_MUTATION = gql`
|
||||
mutation ($id: uuid!, $displayName: String!, $metadata: jsonb) {
|
||||
updateUser(pk_columns: { id: $id }, _set: { displayName: $displayName, metadata: $metadata }) {
|
||||
id
|
||||
displayName
|
||||
metadata
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const Profile = () => {
|
||||
const [mutateUser, { loading: updatingProfile }] = useMutation(UPDATE_USER_MUTATION)
|
||||
|
||||
const updateUserProfile = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
try {
|
||||
await mutateUser({
|
||||
variables: {
|
||||
id: user.id,
|
||||
displayName: `${firstName} ${lastName}`.trim(),
|
||||
metadata: {
|
||||
firstName,
|
||||
lastName
|
||||
}
|
||||
}
|
||||
})
|
||||
toast.success('Updated successfully', { id: 'updateProfile' })
|
||||
} catch (error) {
|
||||
toast.error('Unable to update profile', { id: 'updateProfile' })
|
||||
}
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
Finally, since Hasura has an **allow nothing by default** policy, and we haven't
|
||||
set any permissions yet, our GraphQL mutations would fail.
|
||||
|
||||
So, open the Hasura console from the **Data** tab of your project from [your Nhost dashboard](https://app.nhost.io/). Then, go to the **permissions** tab of the `users` table, type in `user` in the role
|
||||
cell, and click the edit icon on the `select` operation:
|
||||
|
||||

|
||||
|
||||
To restrict the user to read his data only, specify a condition with the
|
||||
user's ID and the `X-Hasura-User-ID` session variable, which is passed with each
|
||||
requests.
|
||||
|
||||

|
||||
|
||||
Next, select the columns you'd like the users to have access to, and click
|
||||
**Save Permissions**.
|
||||
|
||||

|
||||
|
||||
Repeat the same steps on the `update` operation for the `user` role to allow
|
||||
users to update their `displayName` and `metadata` only.
|
||||
|
||||
Finally, to add caching, synchronizing, and updating server state in your Next.js app, let's refactor the user data fetching by using the Apollo client and our GraphQL API instead.
|
||||
|
||||
So, first add the following GraphQL query to retrieve the current user data from the `UserProvider.js` file:
|
||||
|
||||
```js title="UserProvider.js"
|
||||
import { gql } from '@apollo/client'
|
||||
|
||||
const GET_USER_QUERY = gql`
|
||||
query GetUser($id: uuid!) {
|
||||
user(id: $id) {
|
||||
id
|
||||
email
|
||||
displayName
|
||||
metadata
|
||||
avatarUrl
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export function UserProvider() {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
Then, replace the `useUserData` hook with the `useUserId` hook to retrieve the current user's ID only.
|
||||
|
||||
```js title="UserProvider.js"
|
||||
import { useUserId } from '@nhost/nextjs'
|
||||
|
||||
export function UserProvider() {
|
||||
const id = useUserId()
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
Finally, we can run our GraphQL query using the `useQuery` hook and the current user's ID.
|
||||
|
||||
```jsx title="UserProvider.js"
|
||||
// highlight-next-line
|
||||
import { gql, useQuery } from '@apollo/client'
|
||||
|
||||
export function UserProvider({ children = null }) {
|
||||
const id = useUserId()
|
||||
// highlight-start
|
||||
const { loading, error, data } = useQuery(GET_USER_QUERY, {
|
||||
variables: { id },
|
||||
skip: !id
|
||||
})
|
||||
const user = data?.user
|
||||
// highlight-end
|
||||
|
||||
// highlight-start
|
||||
if (error) {
|
||||
return <p>Something went wrong. Try to refresh the page.</p>
|
||||
}
|
||||
if (loading) {
|
||||
return null
|
||||
}
|
||||
// highlight-end
|
||||
|
||||
return <UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
|
||||
}
|
||||
```
|
||||
|
||||
You now have a fully functional Next.js application. Congratulations!
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Did you enjoy Nhost? Give us a star ⭐ on [Github](https://github.com/nhost/nhost). Thank you!
|
||||
- Check out our more in-depth [examples](https://github.com/nhost/nhost/tree/main/examples).
|
||||
- Build your next app with [Nhost](https://app.nhost.io/)!
|
||||
@@ -1,682 +0,0 @@
|
||||
---
|
||||
title: 'Quickstart: React'
|
||||
sidebar_label: React
|
||||
sidebar_position: 1
|
||||
image: /img/og/quickstart-react.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
# Quickstart: React
|
||||
|
||||
## Introduction
|
||||
|
||||
This quickstart guide provides the steps you need to build a simple React app
|
||||
powered by Nhost for the backend. It includes:
|
||||
|
||||
- Database: [PostgreSQL](https://www.postgresql.org/)
|
||||
- Instant GraphQL API: [Hasura](https://hasura.io/)
|
||||
- Authentication: [Hasura Auth](https://github.com/nhost/hasura-auth/)
|
||||
- Storage: [Hasura Storage](https://hub.docker.com/r/nhost/hasura-storage)
|
||||
|
||||
By the end of this guide, you'll have a full-stack app that allows users to log
|
||||
in to access a protected dashboard and update their profile information.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before getting started, let's make sure that your development environment is
|
||||
ready.
|
||||
|
||||
You'll need **Node.js** version 14 or later: [install it from here](https://nodejs.org/en/).
|
||||
|
||||
## Project setup
|
||||
|
||||
### Create a new Nhost project
|
||||
|
||||
import CreateProject from '@site/src/components/create-nhost-project.mdx'
|
||||
|
||||
<CreateProject />
|
||||
|
||||
:::info
|
||||
You can also connect your Nhost project to a Git repository at GitHub. When you do this, any updates you push to your code will automatically be deployed. [Learn more](/platform/git)
|
||||
:::
|
||||
|
||||
## Initialize the app
|
||||
|
||||
### Create a React app
|
||||
|
||||
The simplest way to create a new React application is by using the tool called
|
||||
`create-react-app`, which bootstraps a React app for you without the hassle of
|
||||
configuring everything yourself.
|
||||
|
||||
So, open your terminal, and run the following command:
|
||||
|
||||
```bash
|
||||
npx create-react-app my-nhost-app --template nhost-quickstart
|
||||
```
|
||||
|
||||
:::info
|
||||
This command uses an [existing template](https://github.com/nhost/cra-template-nhost-quickstart), through the `--template` flag, which already contains the React components and pages we'll use for this guide.
|
||||
:::
|
||||
|
||||
You can now `cd` into your project directory:
|
||||
|
||||
```bash
|
||||
cd my-nhost-app
|
||||
```
|
||||
|
||||
And run the development server with the following command:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn start
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
If everything is working fine, your React development server should be running
|
||||
on port 3000. Open [http://localhost:3000](http://localhost:3000) from your
|
||||
browser to check this out.
|
||||
|
||||
### Configure Nhost with React
|
||||
|
||||
To work with Nhost from within our React app, we'll use the
|
||||
[React SDK](https://github.com/nhost/nhost/tree/main/packages/react) provided
|
||||
by Nhost. It's a wrapper around the
|
||||
[Nhost JavaScript SDK](https://github.com/nhost/nhost/tree/main/packages/nhost-js) which
|
||||
gives us a way to interact with our Nhost backend using React hooks.
|
||||
|
||||
You can install the Nhost React SDK with:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/react graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn add @nhost/react graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Next, open your `App.js` file as we'll now configure Nhost inside our app.
|
||||
|
||||
The Nhost React SDK comes with a React provider named `NhostProvider` that
|
||||
makes the authentication state and all the provided React hooks available in our
|
||||
application.
|
||||
|
||||
Use the following code to instantiate a new Nhost client and link it to your
|
||||
Nhost backend:
|
||||
|
||||
```jsx title="src/App.js"
|
||||
import { NhostClient, NhostProvider } from '@nhost/react'
|
||||
|
||||
const nhost = new NhostClient({
|
||||
subdomain: process.env.REACT_APP_NHOST_SUBDOMAIN,
|
||||
region: process.env.REACT_APP_NHOST_REGION
|
||||
})
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<NhostProvider nhost={nhost}>
|
||||
<BrowserRouter>{/* ... */}</BrowserRouter>
|
||||
</NhostProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
```
|
||||
|
||||
Finally, make sure to create an environment variable named
|
||||
`REACT_APP_NHOST_SUBDOMAIN` and `REACT_APP_NHOST_REGION` to store your Nhost domain details:
|
||||
|
||||
```yaml title=".env.local"
|
||||
REACT_APP_NHOST_SUBDOMAIN=[subdomain]
|
||||
REACT_APP_NHOST_REGION=[region]
|
||||
```
|
||||
|
||||
You find your Nhost project's `subdomain` and `region` in the [project overview](https://app.nhost.io):
|
||||
|
||||

|
||||
|
||||
:::caution
|
||||
Don't forget to restart your React server after saving your `.env.local`
|
||||
file to load your new environment variable.
|
||||
:::
|
||||
|
||||
:::info Nhost CLI
|
||||
Do you use the Nhost CLI? Learn how to set `subdomain` and `region` in the [CLI documentation](/cli#subdomain-and-region).
|
||||
:::
|
||||
|
||||
## Build the app
|
||||
|
||||
### Add authentication
|
||||
|
||||
#### 1. Sign-up
|
||||
|
||||
The next step is to allow our users to authenticate into our application.
|
||||
Let's start with implementing the sign-up process.
|
||||
|
||||
For that, we'll use the `useSignUpEmailPassword` hook provided by the Nhost
|
||||
React SDK within our `SignUp` component.
|
||||
|
||||
So, open up the corresponding file from your project, and use the following
|
||||
code:
|
||||
|
||||
```jsx title="src/components/SignUp.js"
|
||||
import styles from '../styles/components/SignUp.module.css'
|
||||
import { useState } from 'react'
|
||||
import { useSignUpEmailPassword } from '@nhost/react'
|
||||
import { Link, Navigate } from 'react-router-dom'
|
||||
import Input from './Input'
|
||||
import Spinner from './Spinner'
|
||||
|
||||
const SignUp = () => {
|
||||
const [firstName, setFirstName] = useState('')
|
||||
const [lastName, setLastName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
||||
const { signUpEmailPassword, isLoading, isSuccess, needsEmailVerification, isError, error } =
|
||||
useSignUpEmailPassword()
|
||||
|
||||
const handleOnSubmit = (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
signUpEmailPassword(email, password, {
|
||||
displayName: `${firstName} ${lastName}`.trim(),
|
||||
metadata: {
|
||||
firstName,
|
||||
lastName
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (isSuccess) {
|
||||
return <Navigate to="/" replace={true} />
|
||||
}
|
||||
|
||||
const disableForm = isLoading || needsEmailVerification
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles['logo-wrapper']}>
|
||||
<img src={process.env.PUBLIC_URL + 'logo.svg'} alt="logo" />
|
||||
</div>
|
||||
|
||||
{needsEmailVerification ? (
|
||||
<p className={styles['verification-text']}>
|
||||
Please check your mailbox and follow the verification link to verify your email.
|
||||
</p>
|
||||
) : (
|
||||
<form onSubmit={handleOnSubmit} className={styles.form}>
|
||||
<div className={styles['input-group']}>
|
||||
<Input
|
||||
label="First name"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
label="Last name"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="email"
|
||||
label="Email address"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
type="password"
|
||||
label="Create password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
|
||||
<button type="submit" disabled={disableForm} className={styles.button}>
|
||||
{isLoading ? <Spinner size="sm" /> : 'Create account'}
|
||||
</button>
|
||||
|
||||
{isError ? <p className={styles['error-text']}>{error?.message}</p> : null}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className={styles.text}>
|
||||
Already have an account?{' '}
|
||||
<Link to="/sign-in" className={styles.link}>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SignUp
|
||||
```
|
||||
|
||||
By default, the user must verify his email address before fully signing up. You can change this setting from your Nhost dashboard.
|
||||
|
||||
#### 2. Sign-in
|
||||
|
||||
Now that new users can sign up for our application, let's see how to allow
|
||||
existing users to sign in with email and password.
|
||||
|
||||
For that, we will use the Nhost hook named `useSignInEmailPassword` inside our
|
||||
`SignIn` component the same way we did with our `SignUp` component. So, here's
|
||||
what your component should look like after applying the changes for the sign-in
|
||||
logic:
|
||||
|
||||
```jsx title="src/components/SignIn.js"
|
||||
import styles from '../styles/components/SignIn.module.css'
|
||||
import { useState } from 'react'
|
||||
import { useSignInEmailPassword } from '@nhost/react'
|
||||
import { Link, Navigate } from 'react-router-dom'
|
||||
import Input from './Input'
|
||||
import Spinner from './Spinner'
|
||||
|
||||
const SignIn = () => {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
||||
const { signInEmailPassword, isLoading, isSuccess, needsEmailVerification, isError, error } =
|
||||
useSignInEmailPassword()
|
||||
|
||||
const handleOnSubmit = (e) => {
|
||||
e.preventDefault()
|
||||
signInEmailPassword(email, password)
|
||||
}
|
||||
|
||||
if (isSuccess) {
|
||||
return <Navigate to="/" replace={true} />
|
||||
}
|
||||
|
||||
const disableForm = isLoading || needsEmailVerification
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles['logo-wrapper']}>
|
||||
<img src={process.env.PUBLIC_URL + 'logo.svg'} alt="logo" />
|
||||
</div>
|
||||
|
||||
{needsEmailVerification ? (
|
||||
<p className={styles['verification-text']}>
|
||||
Please check your mailbox and follow the verification link to verify your email.
|
||||
</p>
|
||||
) : (
|
||||
<form onSubmit={handleOnSubmit} className={styles.form}>
|
||||
<Input
|
||||
type="email"
|
||||
label="Email address"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
type="password"
|
||||
label="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={disableForm}
|
||||
required
|
||||
/>
|
||||
|
||||
<button type="submit" disabled={disableForm} className={styles.button}>
|
||||
{isLoading ? <Spinner size="sm" /> : 'Sign in'}
|
||||
</button>
|
||||
|
||||
{isError ? <p className={styles['error-text']}>{error?.message}</p> : null}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className={styles.text}>
|
||||
No account yet?{' '}
|
||||
<Link to="/sign-up" className={styles.link}>
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SignIn
|
||||
```
|
||||
|
||||
#### 3. Sign-out
|
||||
|
||||
Finally, to allow the users to sign out from the app, we can use the Nhost
|
||||
`useSignOut` hook:
|
||||
|
||||
```jsx title="src/components/Layout.js"
|
||||
import { useSignOut } from '@nhost/react'
|
||||
|
||||
const Layout = () => {
|
||||
const { signOut } = useSignOut()
|
||||
|
||||
const menuItems = [
|
||||
//..
|
||||
{
|
||||
label: 'Logout',
|
||||
onClick: signOut,
|
||||
icon: LogoutIcon
|
||||
}
|
||||
]
|
||||
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
### Protect routes
|
||||
|
||||
Now that we have implemented authentication, we can easily decide who can access
|
||||
certain parts of our application.
|
||||
|
||||
In our case, we'll only allow authenticated users to have access to the `/` and
|
||||
`/profile` routes. All the other users should be redirected to the `/sign-in`
|
||||
page if they try to access those routes.
|
||||
|
||||
To do so, we can create a wrapper component (`ProtectedRoute`) to check the authentication status of the current user using the Nhost SDK:
|
||||
|
||||
```jsx title="src/components/ProtectedRoute.js"
|
||||
import styles from '../styles/components/ProtectedRoute.module.css'
|
||||
import { useAuthenticationStatus } from '@nhost/react'
|
||||
import { Navigate, useLocation } from 'react-router-dom'
|
||||
import Spinner from './Spinner'
|
||||
|
||||
const ProtectedRoute = ({ children }) => {
|
||||
const { isAuthenticated, isLoading } = useAuthenticationStatus()
|
||||
const location = useLocation()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<Spinner />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/sign-in" state={{ from: location }} replace />
|
||||
}
|
||||
|
||||
return children
|
||||
}
|
||||
|
||||
export default ProtectedRoute
|
||||
```
|
||||
|
||||
Then, we can use a [layout route](https://reactrouter.com/docs/en/v6/getting-started/concepts#layout-routes) in our `App.js` file, to wrap the `ProtectedRoute` component around the routes we want to protect:
|
||||
|
||||
```jsx title="src/App.js"
|
||||
import ProtectedRoute from './components/ProtectedRoute'
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<NhostProvider nhost={nhost}>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="sign-up" element={<SignUp />} />
|
||||
<Route path="sign-in" element={<SignIn />} />
|
||||
<Route
|
||||
path="/"
|
||||
// highlight-start
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Layout />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
// highlight-end
|
||||
>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="profile" element={<Profile />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</NhostProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Retrieve user data
|
||||
|
||||
Finally, let's display the information of the authenticated user throughout his
|
||||
dashboard to make the app more personalized.
|
||||
|
||||
Getting the current authenticated user data is quite easy. Indeed, we
|
||||
can use the `useUserData` hook provided by Nhost to do it.
|
||||
|
||||
So, open the `components/Layout.js` file and use this hook like so:
|
||||
|
||||
```js
|
||||
import { useUserData } from '@nhost/react'
|
||||
|
||||
const Layout = () => {
|
||||
const user = useUserData()
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
That's it! The JSX code for rendering the user data (email, display name, etc.)
|
||||
is already included in your components as part of the template you've
|
||||
bootstraped at the beginning of this guide.
|
||||
|
||||
### Update user data
|
||||
|
||||
Nhost provides a GraphQL API through Hasura so that we can query and mutate our
|
||||
data instantly.
|
||||
|
||||
In this tutorial, we'll use the
|
||||
[Apollo GraphQL client](https://www.apollographql.com/) for interacting with
|
||||
this GraphQL API.
|
||||
|
||||
So, start by installing the following dependencies:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/react-apollo @apollo/client
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn add @nhost/react-apollo @apollo/client
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Then, add the `NhostApolloProvider` from `@nhost/react-apollo` into your
|
||||
`App.js` file.
|
||||
|
||||
```jsx title="src/App.js"
|
||||
import { NhostApolloProvider } from '@nhost/react-apollo'
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<NhostProvider nhost={nhost}>
|
||||
<NhostApolloProvider nhost={nhost}>{/* ... */}</NhostApolloProvider>
|
||||
</NhostProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
From there, we can construct our GraphQL query and use the Apollo `useMutation`
|
||||
hook to execute that query when the user submits the form from the profile page:
|
||||
|
||||
```js title="src/pages/Profile.js"
|
||||
import { gql, useMutation } from '@apollo/client'
|
||||
import { toast } from 'react-hot-toast'
|
||||
|
||||
const UPDATE_USER_MUTATION = gql`
|
||||
mutation ($id: uuid!, $displayName: String!, $metadata: jsonb) {
|
||||
updateUser(pk_columns: { id: $id }, _set: { displayName: $displayName, metadata: $metadata }) {
|
||||
id
|
||||
displayName
|
||||
metadata
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const Profile = () => {
|
||||
const [mutateUser, { loading: updatingProfile }] = useMutation(UPDATE_USER_MUTATION)
|
||||
|
||||
const updateUserProfile = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
try {
|
||||
await mutateUser({
|
||||
variables: {
|
||||
id: user.id,
|
||||
displayName: `${firstName} ${lastName}`.trim(),
|
||||
metadata: {
|
||||
firstName,
|
||||
lastName
|
||||
}
|
||||
}
|
||||
})
|
||||
toast.success('Updated successfully', { id: 'updateProfile' })
|
||||
} catch (error) {
|
||||
toast.error('Unable to update profile', { id: 'updateProfile' })
|
||||
}
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
Finally, since Hasura has an **allow nothing by default** policy, and we haven't
|
||||
set any permissions yet, our GraphQL mutations would fail.
|
||||
|
||||
So, open the Hasura console from the **Data** tab of your project from [your Nhost dashboard](https://app.nhost.io/). Then, go to the **permissions** tab of the `users` table, type in `user` in the role
|
||||
cell, and click the edit icon on the `select` operation:
|
||||
|
||||

|
||||
|
||||
To restrict the user to read his own data only, specify a condition with the
|
||||
user's ID and the `X-Hasura-User-ID` session variable, which is passed with each
|
||||
requests.
|
||||
|
||||

|
||||
|
||||
Next, select the columns you'd like the users to have access to, and click
|
||||
**Save Permissions**.
|
||||
|
||||

|
||||
|
||||
Repeat the same steps on the `update` operation for the `user` role to allow
|
||||
users to update their `displayName` and `metadata` only.
|
||||
|
||||
Finally, to add caching, synchronizing, and updating server state in your React app, let's refactor the user data fetching using the Apollo client and our GraphQL API instead.
|
||||
|
||||
So, first add the following GraphQL query to retrieve the current user data from the `Layout` component:
|
||||
|
||||
```js title="src/components/Layout.js"
|
||||
import { gql } from '@apollo/client'
|
||||
|
||||
const GET_USER_QUERY = gql`
|
||||
query GetUser($id: uuid!) {
|
||||
user(id: $id) {
|
||||
id
|
||||
email
|
||||
displayName
|
||||
metadata
|
||||
avatarUrl
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const Layout = () => {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
Then, replace the `useUserData` hook with the `useUserId` hook to retrieve the current user's ID.
|
||||
|
||||
```js title="src/components/Layout.js"
|
||||
import { useUserId } from '@nhost/react'
|
||||
|
||||
const Layout = () => {
|
||||
const id = useUserId()
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
Finally, we can run our GraphQL query using the `useQuery` hook and the current user's ID.
|
||||
|
||||
```jsx title="src/components/Layout.js"
|
||||
// highlight-next-line
|
||||
import { gql, useQuery } from '@apollo/client'
|
||||
|
||||
const Layout = () => {
|
||||
const id = useUserId()
|
||||
// highlight-start
|
||||
const { loading, error, data } = useQuery(GET_USER_QUERY, {
|
||||
variables: { id },
|
||||
skip: !id
|
||||
})
|
||||
const user = data?.user
|
||||
// highlight-end
|
||||
|
||||
//...
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header>{/* ... */}</header>
|
||||
|
||||
<main className={styles.main}>
|
||||
<div className={styles['main-container']}>
|
||||
{/* highlight-start */}
|
||||
{error ? (
|
||||
<p>Something went wrong. Try to refresh the page.</p>
|
||||
) : !loading ? (
|
||||
<Outlet context={{ user }} />
|
||||
) : null}
|
||||
{/* highlight-end */}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
You now have a fully functional React application. Congratulations!
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Did you enjoy Nhost? Give us a star ⭐ on [Github](https://github.com/nhost/nhost). Thank you!
|
||||
- Check out our more in-depth [examples](https://github.com/nhost/nhost/tree/main/examples).
|
||||
- Build your next app with [Nhost](https://app.nhost.io/)!
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,838 +0,0 @@
|
||||
---
|
||||
title: 'Quickstart: Vue'
|
||||
sidebar_label: Vue
|
||||
sidebar_position: 3
|
||||
image: /img/og/quickstart-vue.png
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs'
|
||||
import TabItem from '@theme/TabItem'
|
||||
|
||||
# Quickstart: Vue
|
||||
|
||||
## Introduction
|
||||
|
||||
This quickstart guide provides the steps you need to build a simple Vue app
|
||||
powered by Nhost for the backend. It includes:
|
||||
|
||||
- Database: [PostgreSQL](https://www.postgresql.org/)
|
||||
- Instant GraphQL API: [Hasura](https://hasura.io/)
|
||||
- Authentication: [Hasura Auth](https://github.com/nhost/hasura-auth/)
|
||||
- Storage: [Hasura Storage](https://hub.docker.com/r/nhost/hasura-storage)
|
||||
|
||||
By the end of this guide, you'll have a full-stack app that allows users to log
|
||||
in to access a protected dashboard and update their profile information.
|
||||
|
||||
:::tip
|
||||
You can see the result of this quickstart [in our main repository](https://github.com/nhost/nhost/tree/main/examples/vue-quickstart).
|
||||
|
||||
You can also preview it in the browser: [](https://stackblitz.com/github/nhost/nhost/tree/main/examples/vue-quickstart)
|
||||
:::
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before getting started, let's make sure that your development environment is
|
||||
ready.
|
||||
|
||||
You'll need **Node.js** version 14 or later: [install it from here](https://nodejs.org/en/).
|
||||
|
||||
## Project setup
|
||||
|
||||
### Create a new Nhost app
|
||||
|
||||
import CreateApp from '@site/src/components/create-nhost-project.mdx'
|
||||
|
||||
<CreateApp />
|
||||
|
||||
:::info
|
||||
You can also connect your Nhost project to a Git repository at GitHub. When you do this, any updates you push to your code will automatically be deployed. [Learn more](/platform/git)
|
||||
:::
|
||||
|
||||
## Initialize the app
|
||||
|
||||
### Create a Vue app
|
||||
|
||||
We will use a simple adaptation of [Vitesse Lite](https://github.com/antfu/vitesse-lite), a ready-to-deploy Vite template by Anthony Fu. We can scaffold it with [degit](https://github.com/Rich-Harris/degit).
|
||||
|
||||
Open your terminal, and run the following command:
|
||||
|
||||
```bash
|
||||
npx degit nhost/vue-quickstart my-nhost-app
|
||||
```
|
||||
|
||||
<br />
|
||||
|
||||
:::note Sidebar
|
||||
A completed quickstart example can be be found in the [examples](https://github.com/nhost/nhost/tree/main/examples/vue-quickstart) directory.
|
||||
|
||||
Run the following command in your terminal to create a local copy the example project:
|
||||
|
||||
```bash
|
||||
npx degit nhost/nhost/examples/vue-quickstart my-nhost-app
|
||||
````
|
||||
:::
|
||||
|
||||
|
||||
You can now go into your project directory, install dependencies, and start the development server:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
cd my-nhost-app
|
||||
npm install
|
||||
npm dev
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
cd my-nhost-app
|
||||
yarn
|
||||
yarn dev
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="pnpm" label="pnpm">
|
||||
|
||||
```bash
|
||||
cd my-nhost-app
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
If everything is working fine, your Vue development server should be running
|
||||
on port 3000. Open [http://localhost:3000](http://localhost:3000) from your
|
||||
browser to check this out.
|
||||
|
||||
### Configure Nhost with Vue
|
||||
|
||||
To work with Nhost from within our Vue app, we'll use the
|
||||
[Vue SDK](https://github.com/nhost/nhost/tree/main/packages/vue) provided
|
||||
by Nhost. It's a wrapper around the
|
||||
[Nhost JavaScript SDK](https://github.com/nhost/nhost/tree/main/packages/nhost-js) which
|
||||
gives us a way to interact with our Nhost backend using Vue composables.
|
||||
|
||||
You can install the Nhost Vue SDK with:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/vue graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn add @nhost/vue graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="pnpm" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm add @nhost/vue graphql
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Next, open your `src/main.ts` file as we'll now configure Nhost inside our app.
|
||||
|
||||
The Nhost Vue SDK comes with a `NhostClient` that can be loaded into the Vue application as a plugin.
|
||||
It makes the authentication state and all the provided Vue composables available in our
|
||||
application.
|
||||
|
||||
Ensure the hightlighted code below is present to instantiate a new Nhost client
|
||||
and link it to your Nhost backend:
|
||||
|
||||
```tsx title="src/main.ts"
|
||||
import { createApp } from 'vue'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import routes from 'virtual:generated-pages'
|
||||
// highlight-start
|
||||
import { NhostClient } from '@nhost/vue'
|
||||
// highlight-end
|
||||
import App from './App.vue'
|
||||
|
||||
import '@unocss/reset/tailwind.css'
|
||||
import './styles/main.css'
|
||||
import 'uno.css'
|
||||
|
||||
// highlight-start
|
||||
const nhost = new NhostClient({
|
||||
subdomain: import.meta.env.VITE_NHOST_SUBDOMAIN
|
||||
region: import.meta.env.VITE_NHOST_REGION
|
||||
})
|
||||
// highlight-end
|
||||
|
||||
const app = createApp(App)
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes
|
||||
})
|
||||
app
|
||||
.use(router)
|
||||
// highlight-start
|
||||
.use(nhost)
|
||||
// highlight-end
|
||||
.mount('#app')
|
||||
```
|
||||
|
||||
Finally, rename the existing `.env.example` file as `.env` or `.env.development` and store
|
||||
the environment variables for `subdomain` and `region` in the file like this:
|
||||
|
||||
```yaml title=".env.development"
|
||||
VITE_NHOST_SUBDOMAIN=[subdomain]
|
||||
VITE_NHOST_REGION=[region]
|
||||
```
|
||||
|
||||
You find your Nhost project's `subdomain` and `region` in the [project overview](https://app.nhost.io):
|
||||
|
||||

|
||||
|
||||
:::info Nhost CLI
|
||||
Do you use the Nhost CLI? Learn how to set `subdomain` and `region` in the [CLI documentation](/cli#subdomain-and-region).
|
||||
:::
|
||||
|
||||
## Build the app
|
||||
|
||||
### Add authentication
|
||||
|
||||
#### 1. Sign-up
|
||||
|
||||
The next step is to allow our users to authenticate into our application.
|
||||
Let's start with implementing the sign-up process.
|
||||
|
||||
For that, we'll use the `useSignUpEmailPassword` composable provided by the Nhost
|
||||
Vue SDK within a `/sign-up` page.
|
||||
|
||||
Let's create a new page in your project using the following code:
|
||||
|
||||
```markup title="src/pages/sign-up.vue"
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useSignUpEmailPassword } from '@nhost/vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const { signUpEmailPassword, needsEmailVerification } = useSignUpEmailPassword()
|
||||
const router = useRouter()
|
||||
const firstName = ref('')
|
||||
const lastName = ref('')
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const handleSubmit = async (event: Event) => {
|
||||
event.preventDefault()
|
||||
const { isSuccess } = await signUpEmailPassword(email, password, {
|
||||
metadata: { firstName, lastName }
|
||||
})
|
||||
if (isSuccess)
|
||||
router.push('/')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="needsEmailVerification">
|
||||
Please check your mailbox and follow the verification link to verify your email.
|
||||
</p>
|
||||
|
||||
<form v-else @submit="handleSubmit">
|
||||
<input v-model="firstName" placeholder="First name" class="input" />
|
||||
<br />
|
||||
<input v-model="lastName" placeholder="Last name" class="input" />
|
||||
<br />
|
||||
<input v-model="email" type="email" placeholder="Email" class="input" />
|
||||
<br />
|
||||
<input v-model="password" type="password" placeholder="Password" class="input" />
|
||||
<br />
|
||||
|
||||
<button class="btn-submit" type="submit">
|
||||
Sign up
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
#### 2. Sign-in
|
||||
|
||||
Now that new users can sign up for our application, let's see how to allow
|
||||
existing users to sign in with email and password.
|
||||
|
||||
For that, we will use the Nhost composable named `useSignInEmailPassword` inside a new
|
||||
`sign-in` page the same way we did with our `sign-up` page.
|
||||
|
||||
Let's create a `src/pages/sign-in.vue` component:
|
||||
|
||||
```markup title="src/pages/sign-in.vue"
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useSignInEmailPassword } from '@nhost/vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const { signInEmailPassword, needsEmailVerification } = useSignInEmailPassword()
|
||||
const router = useRouter()
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const handleSubmit = async (event: Event) => {
|
||||
event.preventDefault()
|
||||
const { isSuccess } = await signInEmailPassword(email, password)
|
||||
if (isSuccess)
|
||||
router.push('/')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="needsEmailVerification">
|
||||
Your email is not yet verified. Please check your mailbox and
|
||||
follow the verification link to finish registration.
|
||||
</p>
|
||||
|
||||
<form v-else @submit="handleSubmit">
|
||||
<input v-model="email" type="email" placeholder="Email" class="input" />
|
||||
<br />
|
||||
<input v-model="password" type="password" placeholder="Password" class="input" />
|
||||
<br />
|
||||
|
||||
<button class="btn-submit" type="submit">
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
#### 3. Home page
|
||||
|
||||
Let's also add links to sign up and sign in in our index page.
|
||||
|
||||
```markup title="src/pages/index.vue"
|
||||
<template>
|
||||
<div>
|
||||
<div i-carbon-home text-4xl inline-block />
|
||||
<p>Nhost with Vue</p>
|
||||
<p>
|
||||
<em text-sm op75>Quickstart</em>
|
||||
</p>
|
||||
<div py-4 />
|
||||
<!-- highlight-start -->
|
||||
<router-link class="btn" to="/sign-up">
|
||||
Sign Up
|
||||
</router-link>
|
||||
<br />
|
||||
<router-link class="btn" to="/sign-in">
|
||||
Sign In
|
||||
</router-link>
|
||||
<!-- highlight-end -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
#### 4. Sign-out
|
||||
|
||||
Finally, to allow the users to sign out from the app, we can use the Nhost `useSignOut` composable.
|
||||
We'll also use `useAuthenticationStatus` to show the button only when the user is authenticated:
|
||||
|
||||
```markup title="src/components/Footer.vue"
|
||||
<script setup lang="ts">
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthenticated, useSignOut } from '@nhost/vue'
|
||||
import { isDark, toggleDark } from '~/composables'
|
||||
|
||||
const isAuthenticated = useAuthenticated()
|
||||
const { signOut } = useSignOut()
|
||||
const router = useRouter()
|
||||
const handleSignOut = () => {
|
||||
signOut()
|
||||
router.push('/')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav text-xl mt-6 inline-flex gap-2>
|
||||
<button class="icon-btn !outline-none" @click="toggleDark()">
|
||||
<div v-if="isDark" i-carbon-moon />
|
||||
<div v-else i-carbon-sun />
|
||||
</button>
|
||||
|
||||
<button v-if="isAuthenticated" class="icon-btn !outline-none" @click="handleSignOut">
|
||||
<div i-carbon-logout />
|
||||
</button>
|
||||
</nav>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Protect routes
|
||||
|
||||
Now that we have implemented authentication, we can easily decide who can access
|
||||
certain parts of our application.
|
||||
|
||||
Let's create a profile page that will be only accessible to authenticated users.
|
||||
If an unauthenticated user attempts to load it, it will redirect them to the `/sign-up` page:
|
||||
|
||||
```markup title="src/pages/profile.vue"
|
||||
<template>
|
||||
<div>
|
||||
<div i-carbon-home text-4xl inline-block />
|
||||
<p>Profile page</p>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
Then, we can use a [beforeEach navigation guard](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards) in our `main.ts` file:
|
||||
|
||||
```tsx title="src/main.ts"
|
||||
import { createApp } from 'vue'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import routes from 'virtual:generated-pages'
|
||||
import { NhostClient } from '@nhost/vue'
|
||||
import App from './App.vue'
|
||||
|
||||
import '@unocss/reset/tailwind.css'
|
||||
import './styles/main.css'
|
||||
import 'uno.css'
|
||||
|
||||
const nhost = new NhostClient({
|
||||
subdomain: import.meta.env.VITE_NHOST_SUBDOMAIN,
|
||||
region: import.meta.env.VITE_NHOST_REGION
|
||||
})
|
||||
|
||||
const app = createApp(App)
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes
|
||||
})
|
||||
|
||||
// highlight-start
|
||||
router.beforeEach(async (to) => {
|
||||
if (to.path === '/profile' && !(await nhost.auth.isAuthenticatedAsync())) {
|
||||
return '/sign-in'
|
||||
}
|
||||
return true
|
||||
})
|
||||
// highlight-end
|
||||
|
||||
app
|
||||
.use(router)
|
||||
.use(nhost)
|
||||
.mount('#app')
|
||||
```
|
||||
|
||||
Add a link to the profile page in the index page `/`:
|
||||
|
||||
```markup title="src/pages/index.vue"
|
||||
<template>
|
||||
<div>
|
||||
<div i-carbon-home text-4xl inline-block />
|
||||
<p>Nhost with Vue</p>
|
||||
<p>
|
||||
<em text-sm op75>Quickstart</em>
|
||||
</p>
|
||||
<div py-4 />
|
||||
<!-- highlight-start -->
|
||||
<router-link class="btn" to="/profile">
|
||||
Profile
|
||||
</router-link>
|
||||
<br />
|
||||
<!-- highlight-end -->
|
||||
<router-link class="btn" to="/sign-up">
|
||||
Sign Up
|
||||
</router-link>
|
||||
<br />
|
||||
<router-link class="btn" to="/sign-in">
|
||||
Sign In
|
||||
</router-link>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Retrieve user data
|
||||
|
||||
Finally, let's display the information of the authenticated user throughout their
|
||||
dashboard to make the app more personalized.
|
||||
|
||||
Getting the current authenticated user data is quite easy. Indeed, we can
|
||||
use the `useUserData` composable provided by Nhost to do it.
|
||||
|
||||
When the user is authenticated, it returns the information fetched from the `users` table,
|
||||
such as the display name, the email, or the user's roles. This composable returns `null`
|
||||
until the user is effectively authenticated.
|
||||
|
||||
Let's update the profile page to use it:
|
||||
|
||||
```markup title="src/pages/profile.vue"
|
||||
<!-- highlight-start -->
|
||||
<script setup lang="ts">
|
||||
import { useUserData } from '@nhost/vue'
|
||||
const user = useUserData()
|
||||
</script>
|
||||
<!-- highlight-end -->
|
||||
<template>
|
||||
<div>
|
||||
<div i-carbon-home text-4xl inline-block />
|
||||
<p>Profile page</p>
|
||||
<!-- highlight-start -->
|
||||
<p>
|
||||
<em text-sm op75>Quickstart</em>
|
||||
</p>
|
||||
<div v-if="user" py-4>
|
||||
<p my-4>
|
||||
Hello, {{ user?.displayName }}. Your email is {{ user?.email }}.
|
||||
</p>
|
||||
</div>
|
||||
<!-- highlight-end -->
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Update user data
|
||||
|
||||
Nhost provides a GraphQL API through Hasura so that we can query and mutate our data instantly.
|
||||
|
||||
In this tutorial, we'll use [Vue Apollo v4](https://v4.apollo.vuejs.org) for interacting with
|
||||
this GraphQL API. Nhost comes with a custom Apollo client that syncs the Apollo client with
|
||||
the authentication status of your users.
|
||||
|
||||
So, we start by installing the following dependencies:
|
||||
|
||||
<Tabs groupId="package-manager">
|
||||
<TabItem value="npm" label="npm" default>
|
||||
|
||||
```bash
|
||||
npm install @nhost/apollo @apollo/client graphql graphql-tag @vue/apollo-composable
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="yarn" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn add @nhost/apollo @apollo/client graphql graphql-tag @vue/apollo-composable
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="pnpm" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm add @nhost/apollo @apollo/client graphql graphql-tag @vue/apollo-composable
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Then, create the Apollo client in your `src/main.ts` file, and provide it to your Vue app:
|
||||
|
||||
```tsx title="src/main.ts"
|
||||
import { createApp } from 'vue'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import routes from 'virtual:generated-pages'
|
||||
import { NhostClient } from '@nhost/vue'
|
||||
// highlight-start
|
||||
import { createApolloClient } from '@nhost/apollo'
|
||||
import { DefaultApolloClient } from '@vue/apollo-composable'
|
||||
// highlight-end
|
||||
import App from './App.vue'
|
||||
|
||||
import '@unocss/reset/tailwind.css'
|
||||
import './styles/main.css'
|
||||
import 'uno.css'
|
||||
|
||||
const nhost = new NhostClient({
|
||||
subdomain: import.meta.env.VITE_NHOST_SUBDOMAIN,
|
||||
region: import.meta.env.VITE_NHOST_REGION
|
||||
})
|
||||
|
||||
const app = createApp(App)
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes
|
||||
})
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
if (to.path === '/profile' && !(await nhost.auth.isAuthenticatedAsync())) {
|
||||
return '/sign-in'
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
// highlight-start
|
||||
const apolloClient = createApolloClient({ nhost })
|
||||
// highlight-end
|
||||
|
||||
app
|
||||
.use(router)
|
||||
.use(nhost)
|
||||
// highlight-start
|
||||
.provide(DefaultApolloClient, apolloClient)
|
||||
// highlight-end
|
||||
.mount('#app')
|
||||
```
|
||||
|
||||
From there, we can construct our GraphQL query and use the Apollo `useMutation`
|
||||
composable to execute that query when the user submits the form from the profile page:
|
||||
|
||||
```markup title="src/pages/profile.vue"
|
||||
<script setup lang="ts">
|
||||
// highlight-start
|
||||
import { gql } from '@apollo/client/core'
|
||||
import { useNhostClient, useUserData } from '@nhost/vue'
|
||||
import { useMutation } from '@vue/apollo-composable'
|
||||
import { ref } from 'vue'
|
||||
// highlight-end
|
||||
const user = useUserData()
|
||||
// highlight-start
|
||||
const { nhost } = useNhostClient()
|
||||
|
||||
const UPDATE_USER_MUTATION = gql`
|
||||
mutation ($id: uuid!, $displayName: String!, $metadata: jsonb) {
|
||||
updateUser(
|
||||
pk_columns: { id: $id }
|
||||
_set: { displayName: $displayName, metadata: $metadata }
|
||||
) {
|
||||
id
|
||||
displayName
|
||||
metadata
|
||||
}
|
||||
}
|
||||
`
|
||||
const firstName = ref('')
|
||||
const lastName = ref('')
|
||||
const { mutate, loading, error } = useMutation(UPDATE_USER_MUTATION)
|
||||
|
||||
const updateUserProfile = async (event: Event) => {
|
||||
event.preventDefault()
|
||||
if (user.value) {
|
||||
await mutate({
|
||||
id: user.value.id,
|
||||
displayName: `${firstName.value} ${lastName.value}`.trim(),
|
||||
metadata: {
|
||||
firstName: firstName.value,
|
||||
lastName: lastName.value
|
||||
}
|
||||
})
|
||||
await nhost.auth.refreshSession()
|
||||
}
|
||||
}
|
||||
// highlight-end
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div i-carbon-home text-4xl inline-block />
|
||||
<p>Profile page</p>
|
||||
<p>
|
||||
<em text-sm op75>Quickstart</em>
|
||||
</p>
|
||||
<div v-if="user" py-4>
|
||||
<p my-4>
|
||||
Hello, {{ user?.displayName }}. Your email is {{ user?.email }}.
|
||||
</p>
|
||||
<!-- highlight-start -->
|
||||
<form @submit="updateUserProfile">
|
||||
<input v-model="firstName" placeholder="First name" class="input" />
|
||||
<br />
|
||||
<input v-model="lastName" placeholder="Last name" class="input" />
|
||||
<br />
|
||||
<button className="m-3 text-sm btn" :disabled="loading">
|
||||
Save
|
||||
</button>
|
||||
<div v-if="error">
|
||||
{{ error.message }}
|
||||
</div>
|
||||
</form>
|
||||
<!-- highlight-end -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
:::tip
|
||||
You probably have noticed that we are calling `nhost.auth.refreshSession()` after we updated the
|
||||
user using the GraphQL mutation. The Nhost client only extracts user information from the
|
||||
access token (JWT), that is kept in memory and refreshed every 15 minutes. As user information
|
||||
has been updated, we force an access token refresh so it is kept up to date.
|
||||
:::
|
||||
|
||||
Finally, since Hasura has an **allow nothing by default** policy, and we haven't
|
||||
set any permissions yet, our GraphQL mutations would fail.
|
||||
|
||||
So, open the Hasura console from the **Data** tab of your project from [your Nhost dashboard](https://app.nhost.io/). Then, go to the **permissions** tab of the `users` table, type in `user` in the role cell,
|
||||
and click the edit icon on the `select` operation:
|
||||
|
||||

|
||||
|
||||
To restrict the user to read his own data only, specify a condition with the user's ID and
|
||||
the `X-Hasura-User-ID` session variable, which is passed with each requests.
|
||||
|
||||

|
||||
|
||||
Next, select the columns you'd like the users to have access to, and click
|
||||
**Save Permissions**.
|
||||
|
||||

|
||||
|
||||
:::tip Important
|
||||
Repeat the same steps on the `update` operation for the `user` role to allow
|
||||
users to update their `displayName` and `metadata` only.
|
||||
:::
|
||||
|
||||
### Adding Real-time synchronizing
|
||||
|
||||
To add real-time caching, synchronizing, and updating server state in your Vue app,
|
||||
let's refactor the user data fetching using the Apollo client and our GraphQL API instead.
|
||||
|
||||
First, update the profile page, and replace the `useUserData` composable with the `useUserId`
|
||||
composable to retrieve the current user's ID.
|
||||
|
||||
```ts title="src/pages/profile.vue"
|
||||
// replace `import { useNhostClient, useUserData } from '@nhost/vue'`
|
||||
import { useNhostClient, useUserId } from '@nhost/vue'
|
||||
|
||||
// replace `const user = useUserData()`
|
||||
const id = useUserId()
|
||||
```
|
||||
|
||||
Then import the `computed()` function from Vue.
|
||||
|
||||
```ts title="src/pages/profile.vue"
|
||||
// replace `import { ref } from 'vue'`
|
||||
import { computed, ref } from 'vue'
|
||||
```
|
||||
|
||||
Then and add the highlighted code below to add a GraphQL subscription that retrieves the
|
||||
current user data component:
|
||||
|
||||
```ts title="src/pages/profile.vue"
|
||||
// snip...
|
||||
const { nhost } = useNhostClient()
|
||||
|
||||
// highlight-start
|
||||
const GET_USER_SUBSCRIPTION = gql`
|
||||
subscription GetUser($id: uuid!) {
|
||||
user(id: $id) {
|
||||
id
|
||||
email
|
||||
displayName
|
||||
metadata
|
||||
avatarUrl
|
||||
}
|
||||
}
|
||||
`
|
||||
// highlight-end
|
||||
|
||||
const id = useUserId()
|
||||
|
||||
// highlight-start
|
||||
const { result } = useSubscription(
|
||||
GET_USER_SUBSCRIPTION,
|
||||
computed(() => ({ id: id.value }))
|
||||
)
|
||||
const user = computed(() => result.value?.user)
|
||||
// highlight-end
|
||||
|
||||
// snip...
|
||||
```
|
||||
|
||||
We can now run our GraphQL subscription using the `useSubscription` composable and retrieve
|
||||
the current user's ID.
|
||||
|
||||
The completed `profile.vue` page should look like this:
|
||||
|
||||
```markup title="src/pages/profile.vue"
|
||||
<script setup lang="ts">
|
||||
import { gql } from '@apollo/client/core'
|
||||
import { useNhostClient, useUserId } from '@nhost/vue'
|
||||
import { useMutation, useSubscription } from '@vue/apollo-composable'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const { nhost } = useNhostClient()
|
||||
|
||||
const GET_USER_SUBSCRIPTION = gql`
|
||||
subscription GetUser($id: uuid!) {
|
||||
user(id: $id) {
|
||||
id
|
||||
email
|
||||
displayName
|
||||
metadata
|
||||
avatarUrl
|
||||
}
|
||||
}
|
||||
`
|
||||
const id = useUserId()
|
||||
|
||||
const { result } = useSubscription(
|
||||
GET_USER_SUBSCRIPTION,
|
||||
computed(() => ({ id: id.value }))
|
||||
)
|
||||
const user = computed(() => result.value?.user)
|
||||
|
||||
const UPDATE_USER_MUTATION = gql`
|
||||
mutation ($id: uuid!, $displayName: String!, $metadata: jsonb) {
|
||||
updateUser(
|
||||
pk_columns: { id: $id }
|
||||
_set: { displayName: $displayName, metadata: $metadata }
|
||||
) {
|
||||
id
|
||||
displayName
|
||||
metadata
|
||||
}
|
||||
}
|
||||
`
|
||||
const firstName = ref('')
|
||||
const lastName = ref('')
|
||||
const { mutate, loading, error } = useMutation(UPDATE_USER_MUTATION)
|
||||
|
||||
const updateUserProfile = async (event: Event) => {
|
||||
event.preventDefault()
|
||||
if (user.value) {
|
||||
await mutate({
|
||||
id: user.value.id,
|
||||
displayName: `${firstName.value} ${lastName.value}`.trim(),
|
||||
metadata: {
|
||||
firstName: firstName.value,
|
||||
lastName: lastName.value
|
||||
}
|
||||
})
|
||||
await nhost.auth.refreshSession()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div i-carbon-home text-4xl inline-block />
|
||||
<p>Profile page</p>
|
||||
<p>
|
||||
<em text-sm op75>Quickstart</em>
|
||||
</p>
|
||||
<div v-if="user" py-4>
|
||||
<p my-4>
|
||||
Hello, {{ user.displayName }}. Your email is {{ user.email }}.
|
||||
</p>
|
||||
<form @submit="updateUserProfile">
|
||||
<input v-model="firstName" placeholder="First name" class="input" />
|
||||
<br />
|
||||
<input v-model="lastName" placeholder="Last name" class="input" />
|
||||
<br />
|
||||
<button className="m-3 text-sm btn" :disabled="loading">
|
||||
Save
|
||||
</button>
|
||||
<div v-if="error">
|
||||
{{ error.message }}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
You now have a fully functional Vue application. Congratulations!
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Did you enjoy Nhost? Give us a star ⭐ on [Github](https://github.com/nhost/nhost). Thank you!
|
||||
- Check out our more in-depth [examples](https://github.com/nhost/nhost/tree/main/examples).
|
||||
- Build your next app with [Nhost](https://app.nhost.io/)!
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"label": "Reference",
|
||||
"link": { "type": "generated-index" }
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
title: 'Reference'
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
In this section:
|
||||
|
||||
### Nhost JavaScript SDK
|
||||
|
||||
- [Overview](/reference/javascript)
|
||||
- [Authentication](/reference/javascript/auth)
|
||||
- [Storage](/reference/javascript/storage)
|
||||
- [Functions](/reference/javascript/nhost-js/functions)
|
||||
- [GraphQL](/reference/javascript/graphql)
|
||||
|
||||
### React
|
||||
|
||||
- [Getting started](/reference/react)
|
||||
- [Protecting routes](/reference/react/protecting-routes)
|
||||
- [Apollo GraphQL](/reference/react/apollo)
|
||||
|
||||
### Next.js
|
||||
|
||||
- [Introduction](/reference/nextjs)
|
||||
- [Protecting routes](/reference/nextjs/protecting-routes)
|
||||
- [Architecture](/reference/nextjs/architecture)
|
||||
|
||||
### Vue
|
||||
|
||||
- [Getting started](/reference/vue)
|
||||
- [Protecting routes](/reference/vue/protecting-routes)
|
||||
- [Apollo GraphQL](/reference/vue/apollo)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user