Giter Club home page Giter Club logo

nuxt-nhost's Introduction

NUXT / NHOST

NHOST module for NUXT

DO NOT USE IN PRODUCTION - WIP

ROADMAP

  • init module
  • basic setup / config
  • make composables for client
  • make composables for User / token
  • add middelware with cookie, refresh token
  • add middelware in demo to protect route if not login
  • Auth feature READY
  • Auth refacto ( accessToken != refeshToken)
  • Composables useAccessToken if needed in server side ( JWT / role )
  • make composables for GRAPHQL request ?
  • GRAPHQL feature + demo
  • make composables for storage ?
  • make composables for fonctions ??? Nuxt + serverless on the edge.
  • Basic design for demo / playground
  • publish demo on Netlify
  • Basic test with vitest
  • Add doc, base on DOCUS
  • Publish on npm
  • PR on Nuxt Modules

Nuxt 2

If you are looking for a solution with Nuxt 2, checkout https://github.com/nhost/nuxt

Development

  1. Clone this repository
  2. Install dependencies using yarn install or npm install
  3. Run npm run dev:prepare to generate type stubs.
  4. Use npm run dev to start playground in development mode.

License

MIT License

nuxt-nhost's People

Contributors

xlanex6 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

renovate-bot

nuxt-nhost's Issues

Supporting Cloudflare Workers as deployment target

The problem
@nhost/nhost-js uses Axios. Thus, the Nhost client can't be used in SSR if Nuxt is deployed as a Cloudflare worker.

This leads to await client.auth.refreshSession(refreshToken.value) failing in nhost.server.ts on page reload when SSR is used.

An experimental solution

  1. Add this package: @vespaiach/axios-fetch-adapter
  2. Use the follwing code in composables/useNhostClient.ts
import { NhostClient } from '@nhost/nhost-js';
import { useRuntimeConfig, useNuxtApp } from '#app'

// New: Axios fetch adapter for CF
import axios from 'axios'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'

export const useNhostClient = (): NhostClient => {
  const nuxtApp = useNuxtApp()

  // New: Set the fetchAdapter as default
  axios.defaults.adapter = fetchAdapter

  const { nhost: { backendUrl } } = useRuntimeConfig().public

  if (!nuxtApp._nhostClient) {
    nuxtApp._nhostClient = new NhostClient({
      backendUrl: backendUrl
    })

  }

  return nuxtApp._nhostClient
}

This way, it works both in Miniflare (dev) and deployed as CF Worker.

Caveats

  1. Depending on your NodeJS version, there is no native fetch support (so the local dev build won't work). There must be a check if the code is running on a CF Worker before applying the adapter.
  2. If your domain is on Cloudflare, and you self-host Nhost / hasura-auth, it's very important to set SSL to "full" instead of "flexible" in the domain settings. Otherwise a Worker on app.domain.com can not fetch the hasura-auth backend on api.domain.com - the fetch will always fail (redirect loop).
  3. If the fetch fails, either because of the CF SSL problem or because of no Axios support, there error might be "invalid or expired refresh token" although the token is fine. The error handling is bad for this case, see here: https://github.com/nhost/nhost/blob/main/packages/hasura-auth-js/src/hasura-auth-client.ts#L602 (Edit: something changed there, might be better now)

Cannot access datas in production

Cannot access Nhost datas in production on Netlify

Error messages :

In production, in the browser console, have :

  • 404 POST error : https://PRODUCTION_URL/api/_nhost/session

Tests carried out

  • With Nuxt 2 and Nhost JS SDK is working
  • With Nuxt 3 and Nhost JS SDK is working

Solution ?

I think the problem comes from that we recover the URL of the site (front-end) and not from the API.
Maybe expecting : POST https://API_URL/api/_nhost/session ?

Is working with local build but no longer works in production.

Technos / versions / config : 
- Nuxt 3 : 3.0.0-rc.8
    - ssr : false
- nuxt-nhost : ^1.1.0

Token mismatch after refresh (handling onTokenChanged)

The bug
If the access token get's refreshed by the Nhost client, a hydration mismatch happens (if the access token is displayed) and further requests like page reloads fail, leading to log-out.

nhostClientRefresh
accessKeyMismatch

To Reproduce
Start the playground, login and wait until the token get's refreshed. Then reload or change the page to see the auth fail.

A possible solution
Adding the following code prevents the bug, but also adds an unecassary, second POST to /api/_nhost/session on each page reload.

plugins/nhost.client.ts: adding onTokenChanged in mounted hook

// Once Nuxt app is mounted
nuxtApp.hooks.hook('app:mounted', () => {
    // Listen to Nhost auth changes
    client.auth.onAuthStateChanged(async (event, session) => {
        await setServerSession(event, session)
        const nhostUser = client.auth.getUser()
        user.value = nhostUser
    })

    // Listen to Nhost token changes
    client.auth.onTokenChanged(async (session) => {
        await setServerSession('TOKEN_CHANGED', session)
        const nhostUser = client.auth.getUser()
        user.value = nhostUser
    })
})

server/api/_nhost/session.ts: adding TOKEN_CHANGED handler

if (signEvent === 'TOKEN_CHANGED') {
    if (!session) {
        throw new Error('Auth session missing!')
    }
    setCookie(
        event,
        `${cookieOptions.name}-access-token`,
        session.refreshToken, {
            domain: cookieOptions.domain,
            maxAge: cookieOptions.lifetime ?? 0,
            path: cookieOptions.path,
            sameSite: cookieOptions.sameSite
        }
    )
}

Right now, I can't think of a clean way to prevent the duplicated POST to /api/_nhost/session.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.