nuxt-nhost
nuxt-nhost copied to clipboard
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
- Add this package: @vespaiach/axios-fetch-adapter
- 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
- 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.
- 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).
- 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)
@pk992 Thanks so much for your work
can you make a PR to keep your work visible in the project ?
I think we can explore also jetbridge/axios-jwt
Sorry, my time is very limited at the moment. :( Both this and the fix from #2 are very "quick and dirty" but allowed me to run it in a (beta) production environment.
The problem with the above solution: Vite will throw a ERR_MODULE_NOT_FOUND
error if this fix is present in dev. Maybe because the native fetch is not found in @vespaiach/axios-fetch-adapter
.
Wrapping it in a if/else like this still throws that error:
if(useRuntimeConfig().runningOnCF) { axios.defaults.adapter = fetchAdapter }
So right now I uncomment this line before deploying...
Update: Tested with 3.0.0-rc.11
, no Vite errors now.
Nice thanks so much
my time was also limited, but i will play OS in october.
i will do my best based on your work 🙏