Skip to content

Instantly share code, notes, and snippets.

@isaumya
Created October 27, 2019 16:47
Show Gist options
  • Save isaumya/cecabfe987b314ecca6c59b655b3093e to your computer and use it in GitHub Desktop.
Save isaumya/cecabfe987b314ecca6c59b655b3093e to your computer and use it in GitHub Desktop.
Add HTTP 2 Server Push to Nuxt JS Application (Universal Mode) - Tested in Zeit Now

How to do HTTP/2 Server Push in Nuxt.JS App (Tested in Universal Mode & Hosted in Zeit Now)

While developing my Nuxt.js app, the one thing I tried to do most was HTTP/2 Server Push, as I am hosting my app on Zeit Now which does support both HTTP/2 and Server Push. The main reason I wanted to do it was I was using Bootstrap Vue on my project. Whcih add the Bootstrap CSS + Bootstrap Vue's own custom CSS as inline style to the document which was making the document huge. Moreover in bootstrap vue you can do bootstrapCSS: false which will not add the Bootstrap's default CSS to your page, but it will add it's own custom CSS.

Also, in my nuxt have I had a lot of CSS at the component/layout level, which are also getting added to the document as inline style. It was getting crazy. At this point I can either load the bootstrap from a CDN which costed me another external request or I can host it myself (Zeit does have CDN) on my own CDN and then do HTTP/2 server push. So, that is what I diid. I also load a style on my home page only which I again pushed just for the home page.

Few Things To Note:

  • These files are in my /static/css/ folder, so they are not being handelled by webpack
  • I am adding these css using the head tag of Nuxt which just like you add meta tags

Time to Add the Code

Here is the code that I have added in my nuxt.config.js

// other nuxt configs....
render: {
  // HTTP2: https://nuxtjs.org/api/configuration-render/#http2
  http2: {
    push: true,
    pushAssets: (req) => {
      const assetsToPush = ['</css/bootstrap.min.css>; rel=preload; as=style']

      if (req.url === '/') {
        assetsToPush.push(
          '</css/placeholder-loading.min.css>; rel=preload; as=style'
        )
      }

      return assetsToPush
    }
  }
},
// other nuxt configs....

HTTP/2 Server Push In Action (Screenshot)

Take a look. Hope this helps other Nuxt JS developers.

Chrome Dev Tool Network Tab Chrome Dev Tool Network Request Detaiils Trying with nghttp

@chaderenyore
Copy link

Hi does this still currently work with nuxt 3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment