Nuxt HTTP Proxy Module
- Nuxt 3
yarn add --dev @privyid/nhp
Then, add into nuxt.config.ts
modules
export default defineNuxtConfig({
modules: ['@privyid/nhp'],
})
Create new server config
npx nhp init
import { defineServer } from '@privyid/nhp/core'
export default defineServer([
{
name : 'example',
baseUrl : '/api/example',
targetUrl: 'https://reqres.in/api/',
},
])
NHP provide util defineEventInterceptor
for onProxyReq
and onProxyRes
, it will translate the handler to H3 compability event.
So, you can use all utilities from H3
import { getCookie, setHeader } from 'h3'
import { defineServer, defineEventInterceptor } from '@privyid/nhp/core'
export default defineServer([
{
name : 'bin',
baseUrl : '/api/bin',
targetUrl : 'https://httpbin.org',
onProxyReq: defineEventInterceptor((proxyEvent, event) => {
const token = getCookie(event, 'oauth/token')
if (token)
setHeader(proxyEvent, 'Authorization', `Bearer ${token}`)
}),
},
])
Dynamic Proxy is special type proxy, which can dynamically target server based on query params url
. It usefull for proxy download server which ussually changes alltime.
Example:
export default defineServer([
{
name : 'force-download',
baseUrl : '/force/download',
proxyType : 'dynamic',
allowFrom : ['my.cdn.com', 's3.amazon.com'], // or using string with delimeter ;
downloadHeader: true,
downloadExt : '.pdf',
},
])
Then, you can access /force/download?url=http://my.cdn.com/xxxxx/
NHP include code generator to transform OpenAPI v2 to Typescript. Just add schemaURL
in your server then run npx nhp schema
,
export default defineServer([
{
name : 'server-b',
baseUrl : '/api/server-b',
// ...
// Using local json
schemaUrl: './path/doc.json',
},
{
name : 'server-a',
baseUrl : '/api/server-a',
// ...
// Using remote schema
schemaUrl: 'http://server-a.dev/swagger/doc.json',
},
])
- Clone this repository
- Play Nyan Cat in the background (really important!)
- Enable Corepack using
corepack enable
(usenpm i -g corepack
for Node.js < 16.10) - Run
yarn install
- Run
yarn dev:prepare
to generate type stubs. - Use
yarn dev
to start playground in development mode.