How do I set preload headers in Next.js?

Viewed 1240

How do I set preload headers in Next.js when the files have random build names?

I've seen from the page source that the static files are preloaded using link tags in the html. I'd much rather have these preloaded in the headers, as that also enables HTTP/2 Server Push.

According to the documentation, you can set custom headers in next.config.js. This is fine, but the main problem is that the file names get random strings every build.

For example, I've also got some local font files that I'd like to push, aswell as the CSS file generated by Tailwind.

How would you set preload headers for the resources in Next.js?

EDIT:

I have managed to hardcode font files in the headers, as these get to keep their random names on rebuild. Tailwind CSS seems to be impossible to hardcode this way, as it gets a new name right after I rebuild. I guess I could modify the build folder in that case, but both of these methods are less than ideal.

Why isn't this a more common issue with people using React/Next.js? As far as I know, Using HTTP/2 Server Push makes everything much faster as long as the server supports it.

1 Answers

Here is a working (but is it efficient?) solution, requiring to setup an Apache2 or NGINX reverse proxy:

  • Use a custom server.
  • Intercept the response body, search <link rel=preload> HTML tags, and set for each link a Link HTTP header. You could use this library.
  • Configure the reverse proxy (NGINX or Apache2) to automatically push resources by intercepting Link HTTP headers.

See also : https://github.com/vercel/next.js/issues/2961

Related