Netlify functions for SSR of meta tags


I’m currently building a SPA and hosting it on Netlify. So far all is going great. Now I’m thinking about how can I provide basic SEO / OG needs, mainly just generate the right <meta> tags on the server. I don’t really need a full SSR of the entire app, just SSR the meta tags and I can completely hardcode it, after all, this meta tag logic does not even need to be duplicated within the client app, the meta tags don’t need to change on client-side transitions (AFAIK).

I know I could be using Netlify Prerendering to do a full SSR prerender of the app, meta tags included. But that approach has two downsides:

  1. The HTML can get stale. I need to bust cache ASAP after the user edits their data via API.
  2. I’d have to put the meta rendering logic in my client-side code and it would increase the bundle size. Wiring that logic on the client is more complex than a simple string concat on the server.

So that’s why I’m looking at Netlify Functions as a promising solution to my problem! After briefly looking at them, it seems to me like they’re primarily focused on JSON serving than HTML serving but maybe it could still be a good match?

Basically, I’d need a wildcard lambda that would check the URL and either just serve the HTML skeleton, or do a node-fetch, open the index.html, split it and inject as some tags there and then serve. Is that doable? Would such a lambda then have to even take care of serving assets? Unfortunately due to my routing needs, I’d need to run it at /* to render pages like

Thanks a ton! I’ve been a big fan of Netlify since its beginnings.

Hiya @martinmalinda and sorry to be slow to get back to you!

That pattern isn’t dumb or an anti-pattern, and your thinking makes sense - our prerendering service is a bit heavyweight for you, impossible for you to clear cache on (you’d need to use a different service like if you update that content often - we assert that most people don’t, so we have a hardwired 24-48h cache for requests that are prerendered).

Functions, though, can return ANY content-type - images, html, pdf’s, etc - but you will need to set the content-type header and return it along with any other headers you want. It’s also usually the case that the function would need to return the ENTIRE page, since to manipulate content-type, you’d need to be in control of the headers which you aren’t if you access the function e.g. via XHR during page loading (you could of course take a JSON response and reformat it as HTML within the page content, but my understanding is that you might have trouble getting the OG stuff into the <head> in a way that crawlers would use. I don’t fully understand how it works - and your use case may be different, so take this parenthetical with a grain of salt!)