Embedding NextJS in Hugo

This post explains how we integrated NextJS interactive widgets into a Hugo static site.

Architecture

The site uses Hugo as the primary static site generator with the PaperMod theme. NextJS applications are embedded via a custom Hugo shortcode.

The Shortcode

The custom nextjs-app shortcode (layouts/shortcodes/nextjs-app.html) renders an iframe pointing to the NextJS application:

{{- $path := default "/interactive-widget" (.Get "path") -}}
{{- $height := default "400" (.Get "height") -}}

{{- if hugo.IsServer -}}
  <!-- Dev: iframe to localhost:3000 -->
  <iframe src="http://localhost:3000{{ $path }}" ...></iframe>
{{- else -}}
  <!-- Production: serve pre-built static files -->
  <iframe src="/nextjs{{ $path }}/index.html" ...></iframe>
{{- end -}}

Development Workflow

  1. Start Hugo: hugo server (port 1313)
  2. Start NextJS: next dev (port 3000)
  3. Hugo pages with {{< nextjs-app >}} load the NextJS widget via iframe

Production Build

cd nextjs-app && next build       # generates out/
cp -r out ../hugo-site/static/nextjs
cd ../hugo-site && hugo           # final site with embedded widget

Try It Yourself

Visit the Interactive Demo page to see the widget in action.