Skip to content

privy-open-source/nhp

Repository files navigation

NHP

npm version npm downloads License Nuxt

Nuxt HTTP Proxy Module

Compabilities

  • Nuxt 3

Instalation

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

Usage

Simple Usage

import { defineServer } from '@privyid/nhp/core'

export default defineServer([
  {
    name     : 'example',
    baseUrl  : '/api/example',
    targetUrl: 'https://reqres.in/api/',
  },
])

Intercept Requests and Response

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

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/

Schema Code-Generator (Swagger)

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',
  },
])

See example and result here

Contribution

  • Clone this repository
  • Play Nyan Cat in the background (really important!)
  • Enable Corepack using corepack enable (use npm 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.

License

MIT License