Skip to content

Instantly share code, notes, and snippets.

@yshrsmz
Last active January 25, 2023 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yshrsmz/dd4a2f267ada3ef866f07fba4d862121 to your computer and use it in GitHub Desktop.
Save yshrsmz/dd4a2f267ada3ef866f07fba4d862121 to your computer and use it in GitHub Desktop.

turns out we simply use nitro.devProxy.

At first hostRewrite option seems to rewrite request header, but it actually rewrites host field of the response header. So we need to manually pass headers option.

https://github.com/http-party/node-http-proxy

const endpoint = 'https://api.example.com/graphql'
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  nitro: {
    devProxy: {
      // GraphQL Proxy Endpoint
      '/api/graphql': {
        target: endpoint,
        headers: {
          host: 'api.example.com',
        },
        cookieDomainRewrite: '',
      },
    },
  },
  runtimeConfig: {
    graphqlEndpoint: endpoint,
    public: {
      graphqlEndpoint: 'http://localhost:3000/api/graphql',
    },
  },
})

below snippets are just for reference.

import consola from 'consola'
import {
H3Event,
getMethod,
getHeaders,
readRawBody,
defineEventHandler,
setResponseHeaders,
} from 'h3'
// graphql proxy endpoint
export default defineEventHandler(async (event: H3Event) => {
const method = getMethod(event)
const headers = getHeaders(event)
const body = await readRawBody(event)
const endpoint = useRuntimeConfig().graphqlEndpoint
const host = new URL(endpoint).host
consola.log({ method, headers, body, endpoint, host })
const newHeaders: Record<string, string> = {
...headers,
host,
origin: host,
}
// delete connection header
// https://github.com/nodejs/undici/issues/1470
delete newHeaders.connection
try {
const res = await $fetch.raw(endpoint, {
method,
headers: newHeaders,
body,
})
const resHeaders: Record<string, string> = {}
res.headers.forEach((value, key) => {
resHeaders[key] = value
})
setResponseHeaders(event, resHeaders)
return res
} catch (e) {
consola.error('graphql proxy error:', e)
throw createError({
statusCode: 500,
statusMessage: (e as any).message ?? 'Internal Server Error',
})
}
})
const isDev = process.env.NODE_ENV !== 'production'
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
serverHandlers: [
...(isDev
? [
// GraphQL Proxy endpoint for dev server
// devServerHandlers does not offer useRuntimeConfig, so we need to manually switch it.
{
route: '/api/graphql',
method: 'post',
handler: './server/dev/graphql.post',
},
]
: []),
],
runtimeConfig: {
graphqlEndpoint: '',
public: {
graphqlEndpoint: 'http://localhost:3000/api/graphql',
},
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment