Repository: nuxt/nuxt.js
Pull request #7214 (2020-04-13 14:40:27)

feat(server): add custom HTTP headers into error response
<!--- Provide a general summary of your changes in the title above -->
This PR add the capability to set a list of custom HTTP header on Error middleware when `throw error`.

## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (a non-breaking change which fixes an issue)
- [x] New feature (a non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)


## Description
<!--- Describe your changes in detail -->
<!--- Why is this change required? What problem does it solve? -->
<!--- If it resolves an open issue, please link to the issue here. For example "Resolves: #1337" -->
Resolves: #7213

## Checklist:
<!--- Put an `x` in all the boxes that apply. -->
<!--- If your change requires a documentation PR, please link it appropriately -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [x] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly. (PR: #)
- [x] I have added tests to cover my changes (if not applicable, please state why)
- [x] All new and existing tests are passing.



codecov-io: # [Codecov](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=h1) Report
> Merging [#7214](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=desc) into [dev](https://codecov.io/gh/nuxt/nuxt.js/commit/c02ded2d8622c290ba28c696d363426b825a0977&el=desc) will **increase** coverage by `0.03%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/nuxt/nuxt.js/pull/7214/graphs/tree.svg?width=650&height=150&src=pr&token=nGD1PtMB3M)](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##              dev    #7214      +/-   ##
==========================================
+ Coverage   62.83%   62.86%   +0.03%     
==========================================
  Files          84       84              
  Lines        3406     3409       +3     
  Branches      930      931       +1     
==========================================
+ Hits         2140     2143       +3     
  Misses       1018     1018              
  Partials      248      248              
```

| Flag | Coverage Δ | |
|---|---|---|
| #unittests | `62.86% <100.00%> (+0.03%)` | :arrow_up: |

| [Impacted Files](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [packages/server/src/middleware/error.js](https://codecov.io/gh/nuxt/nuxt.js/pull/7214/diff?src=pr&el=tree#diff-cGFja2FnZXMvc2VydmVyL3NyYy9taWRkbGV3YXJlL2Vycm9yLmpz) | `98.30% <100.00%> (+0.09%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=footer). Last update [c02ded2...7f54caa](https://codecov.io/gh/nuxt/nuxt.js/pull/7214?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/packages/server/src/middleware/error.js b/packages/server/src/middleware/error.js
index 82c7028a0..05e61ffaa 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')
   }


Test patch:
diff --git a/packages/server/test/middleware/error.test.js b/packages/server/test/middleware/error.test.js
index ed597bdb1..fd8e5a09d 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,