Akryum / vue-cli-plugin-ssr

:sparkles: Simple SSR plugin for Vue CLI
https://vue-cli-plugin-ssr.netlify.com/
MIT License
444 stars 69 forks source link

Fix HTTP server errors when trying to do a HTTP redirect from components #289

Open sneko opened 2 years ago

sneko commented 2 years ago

Hi,

It's to fix this issue when doing HTTP redirections:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:482:11)
    at ServerResponse.header (/Users/XXXXXXXXXX/Documents/YYYYYYY/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/Users/XXXXXXXXXX/Documents/YYYYYYY/node_modules/express/lib/response.js:170:12)
    at renderer.renderToString (/Users/XXXXXXXXXX/Documents/YYYYYYY/node_modules/@akryum/vue-cli-plugin-ssr/lib/app.js:119:15)
    at /Users/XXXXXXXXXX/Documents/YYYYYYY/node_modules/vue-server-renderer/build.dev.js:9536:15

It was not critical in the past (had this 2 years ago https://github.com/Akryum/vue-cli-plugin-ssr/issues/144#issuecomment-601103458), it was just logging things into the console. But since I upgraded some Vue dependencies the "simple log" is now something making the server crashes.

Note: my previous version of vue-server-renderer was v2.6.11 and I tried upgrading to v2.6.14. Don't know which change exactly breaks things... but it's fine with this PR 😄

So to avoid being stuck in a previous version I did a little trick to always respect values that could be passed to the res object.

Hope this helps even if the repo is no longer maintained.

In the meantime if you want to you it you can use a specific branch with some patches I made:

yarn add "@akryum/vue-cli-plugin-ssr@https://github.com/sneko/vue-cli-plugin-ssr#fix/http-redirections"

👍

JeffJassky commented 9 months ago

Here was my hacky solution that didn't require changing the main libs:

in vue.config.js:

module.exports = {
  pluginOptions: {
    ssr: {
      onRender(res, context){
        if(context._routeRedirect){
          res.redirect(301, context._routeRedirect); // do the redirect
          const send = res.send; // store local reference to original send method
          // override send method to prevent headers from being sent
          res.send = function(){
            res.send = send; // restore the original send method for subsequent calls
          }
        }
      },
      ... other configs
    }
  }
}