nuxtjs set response header for 200 status code only

Viewed 635

In nuxtjs, in SSR mode, where/how can I set custom response headers for an endpoint only for 200 OK response code?

There are cases where something goes wrong like 404 not found pages, or 500 internal server error pages, for those I do not want in any circumstances to set the custom header. I need to set X-Accel-Expires response header for 200 response code to tell nginx to cache it and for how long, I dont want errors to be cached.

Currently I'm solving it with the following custom module where I explicitly overwrite previously set X-Accel-Expires with 0 (aka. to disable caching) :

//modules/get-rid-off-custom-header-module/index.js

module.exports = function nuxtCustomHeaders(options) {
    const nuxt = this.nuxt;

    const renderer = nuxt.renderer;
    const renderRoute = renderer.renderRoute.bind(renderer);

    renderer.renderRoute = async function(route, context) {
        try {
            const result = await renderRoute(route, context);

            if (context.nuxt.error) {//eg. we got 404 page
                context.res.setHeader('X-Accel-Expires', '0');
            }

            return result;
        } catch(e) {//rendering failed, 500 internal server error
            context.res.setHeader('X-Accel-Expires', '0');
            throw e;
        }
    };
};

But the above solution just seems to be wrong. I'm hacking nuxt. How this functionality can be achieved cleanly?

0 Answers
Related