diff --git a/packages/server/src/middleware/error.js b/packages/server/src/middleware/error.js index 82c7028a0d..05e61ffaa7 100644 --- a/packages/server/src/middleware/error.js +++ b/packages/server/src/middleware/error.js @@ -10,7 +10,8 @@ export default ({ resources, options }) => async function errorMiddleware (err, const error = { statusCode: err.statusCode || 500, message: err.message || 'Nuxt Server Error', - name: !err.name || err.name === 'Error' ? 'NuxtServerError' : err.name + name: !err.name || err.name === 'Error' ? 'NuxtServerError' : err.name, + headers: err.headers } const sendResponse = (content, type = 'text/html') => { @@ -21,6 +22,13 @@ export default ({ resources, options }) => async function errorMiddleware (err, res.setHeader('Content-Length', Buffer.byteLength(content)) res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate') + // Error headers + if (error.headers) { + for (const name in error.headers) { + res.setHeader(name, error.headers[name]) + } + } + // Send Response res.end(content, 'utf-8') } diff --git a/packages/server/test/middleware/error.test.js b/packages/server/test/middleware/error.test.js index ed597bdb11..fd8e5a09d3 100644 --- a/packages/server/test/middleware/error.test.js +++ b/packages/server/test/middleware/error.test.js @@ -49,6 +49,7 @@ describe('server: errorMiddleware', () => { const params = createParams() const errorMiddleware = createErrorMiddleware(params) const error = new Error() + error.headers = { 'Custom-Header': 'test' } const ctx = createServerContext() await errorMiddleware(error, ctx.req, ctx.res, ctx.next) @@ -56,10 +57,11 @@ describe('server: errorMiddleware', () => { expect(consola.error).toBeCalledWith(error) expect(ctx.res.statusCode).toEqual(500) expect(ctx.res.statusMessage).toEqual('NuxtServerError') - expect(ctx.res.setHeader).toBeCalledTimes(3) + expect(ctx.res.setHeader).toBeCalledTimes(4) expect(ctx.res.setHeader).nthCalledWith(1, 'Content-Type', 'text/html; charset=utf-8') expect(ctx.res.setHeader).nthCalledWith(2, 'Content-Length', Buffer.byteLength('error template')) expect(ctx.res.setHeader).nthCalledWith(3, 'Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate') + expect(ctx.res.setHeader).nthCalledWith(4, 'Custom-Header', 'test') expect(params.resources.errorTemplate).toBeCalledTimes(1) expect(params.resources.errorTemplate).toBeCalledWith({ status: 500,