UNPKG

1.73 kBJavaScriptView Raw
1const Proxy = require('http-proxy-middleware')
2const consola = require('consola')
3
4const logProvider = consola.withScope('nuxt:proxy')
5
6// Redirect info ~> debug
7logProvider.info = logProvider.debug
8
9module.exports = function nuxtProxy (options) {
10 if (!this.options.proxy) {
11 // No proxy defined
12 return
13 }
14
15 this.nuxt.hook('generate:before', () => {
16 consola.warn('This module does not work in generated mode')
17 })
18
19 // Defaults
20 const defaults = Object.assign(
21 {
22 // Required for virtual hosted sites
23 changeOrigin: true,
24 // Proxy webSockets
25 ws: true,
26 // Use consola as default logger
27 logProvider: () => logProvider
28 },
29 options
30 )
31
32 delete defaults.src
33
34 // Normalize options.proxy to middleware arguments
35 const applyDefaults = o => Object.assign({}, defaults, o)
36 const normalizeTarget = o => (typeof o === 'object' ? o : { target: o })
37
38 const proxy = []
39 if (Array.isArray(this.options.proxy)) {
40 // Array mode
41 this.options.proxy.forEach(p => {
42 if (Array.isArray(p)) {
43 proxy.push([p[0], applyDefaults(normalizeTarget(p[1]))])
44 } else {
45 proxy.push([p, applyDefaults()])
46 }
47 })
48 } else {
49 // Object mode
50 Object.keys(this.options.proxy).forEach(context => {
51 proxy.push([
52 context,
53 applyDefaults(normalizeTarget(this.options.proxy[context]))
54 ])
55 })
56 }
57
58 // Register middleware
59 proxy.forEach(args => {
60 // https://github.com/chimurai/http-proxy-middleware
61 const middleware = Proxy.apply(undefined, args)
62 middleware.prefix = false // Don't add router base
63 this.options.serverMiddleware.push(middleware)
64 })
65}
66
67module.exports.meta = require('../package.json')