Headers

    Headers allow you to set custom HTTP headers for an incoming request path.

    To set custom HTTP headers you can use the key in next.config.js:

    • source is the incoming request path pattern.
    • headers is an array of header objects with the key and value properties.

    If two headers match the same path and set the same header key, the last header key will override the first. Using the below headers, the path /hello will result in the header x-hello being world due to the last header value set being world.

    1. module.exports = {
    2. async headers() {
    3. return [
    4. {
    5. source: '/:path*',
    6. headers: [
    7. {
    8. key: 'x-hello',
    9. value: 'there',
    10. },
    11. ],
    12. },
    13. {
    14. source: '/hello',
    15. headers: [
    16. {
    17. key: 'x-hello',
    18. value: 'world',
    19. ],
    20. },
    21. ],
    22. },
    23. }

    Path matches are allowed, for example /blog/:slug will match /blog/hello-world (no nested paths):

    1. module.exports = {
    2. async headers() {
    3. return [
    4. {
    5. source: '/blog/:slug*',
    6. headers: [
    7. {
    8. key: 'x-slug',
    9. value: ':slug*', // Matched parameters can be used in the value
    10. },
    11. {
    12. key: 'x-slug-:slug*', // Matched parameters can be used in the key
    13. value: 'my other custom header value',
    14. },
    15. ],
    16. },
    17. ],
    18. },
    19. }

    To match a regex path you can wrap the regex in parenthesis after a parameter, for example /blog/:slug(\\d{1,}) will match but not /blog/abc:

    When leveraging basePath support with headers each source is automatically prefixed with the basePath unless you add basePath: false to the header:

    1. module.exports = {
    2. async headers() {
    3. return [
    4. {
    5. source: '/with-basePath', // becomes /docs/with-basePath
    6. headers: [
    7. {
    8. key: 'x-hello',
    9. value: 'world',
    10. },
    11. ],
    12. },
    13. {
    14. source: '/without-basePath', // is not modified since basePath: false is set
    15. headers: [
    16. {
    17. key: 'x-hello',
    18. value: 'world',
    19. },
    20. ],
    21. basePath: false,
    22. },
    23. ]
    24. }