diff --git a/packages/server/src/server.js b/packages/server/src/server.js index 6e552767f3..4370cce259 100644 --- a/packages/server/src/server.js +++ b/packages/server/src/server.js @@ -176,7 +176,17 @@ export default class Server { // Resolve handler setup as string (path) if (typeof handler === 'string') { try { - handler = this.nuxt.resolver.requireModule(middleware.handler || middleware) + const requiredModuleFromHandlerPath = this.nuxt.resolver.requireModule(handler) + + // In case the "handler" is not derived from an object but is a normal string, another object with + // path and handler could be the result + + // If the required module has handler, treat the module as new "middleware" object + if (requiredModuleFromHandlerPath.handler) { + middleware = requiredModuleFromHandlerPath + } + + handler = requiredModuleFromHandlerPath.handler || requiredModuleFromHandlerPath } catch (err) { if (!this.options.dev) { throw err[0] diff --git a/test/fixtures/module/modules/middleware/midd3.js b/test/fixtures/module/modules/middleware/midd3.js new file mode 100644 index 0000000000..9841db4b91 --- /dev/null +++ b/test/fixtures/module/modules/middleware/midd3.js @@ -0,0 +1,7 @@ +export default { + path: '/midd3', + handler(req, res) { + res.write('Be creative when writing test strings! Hey Mama :wave:') + res.end() + } +} diff --git a/test/fixtures/module/nuxt.config.js b/test/fixtures/module/nuxt.config.js index cf3ef40c88..09540fb8ed 100644 --- a/test/fixtures/module/nuxt.config.js +++ b/test/fixtures/module/nuxt.config.js @@ -12,7 +12,10 @@ export default { }, ['./modules/template', { baz: 'ping' }] ], - serverMiddleware: ['./modules/middleware/midd2'], + serverMiddleware: [ + './modules/middleware/midd2', + '~/modules/middleware/midd3' + ], hooks(hook) { hook('ready', (nuxt) => { nuxt.__ready_called__ = true diff --git a/test/unit/module.test.js b/test/unit/module.test.js index 69b69da146..8e17e566b9 100644 --- a/test/unit/module.test.js +++ b/test/unit/module.test.js @@ -54,6 +54,11 @@ describe('module', () => { expect(response).toBe('It works!') }) + test('serverMiddleware with path', async () => { + const response = await rp(url('/midd3')) + expect(response).toBe('Be creative when writing test strings! Hey Mama :wave:') + }) + test('Hooks - Use external middleware before render', async () => { const response = await rp(url('/use-middleware')) expect(response).toBe('Use external middleware')