Gopal Verma

Rendering Jupyter Notebooks in Next.js

Publishing data science experiments, machine learning research, or mathematical explorations directly from Jupyter Notebooks (.ipynb) onto a personal React / Next.js website often feels clunky. Most developers resort to embedding heavy third-party <iframe> viewers (nbviewer, Google Colab embeds) or manually converting notebooks to Markdown every time they make an edit.

In this note, we walk through how .ipynb files are rendered natively on this website—giving you server-side Shiki syntax highlighting (with instant dark/light mode support), KaTeX math equations, Pandas DataFrame HTML tables, Matplotlib / Seaborn plots, collapsible code cells, and an automatic Table of Contents, simply by dropping any .ipynb file into a folder.

Why Render .ipynb Server-Side in Next.js?

  1. Zero Client-Side Parser Overhead: Syntax highlighting (shiki) and LaTeX compilation (katex) run on the server at build/request time inside Next.js Server Components.
  2. Native Theme Integration: Instead of an mismatched white iframe inside a dark-mode site, every Markdown paragraph, code block, table, and output matches your Tailwind CSS design tokens.
  3. Drop-In Workflow: You don't need an external jupyter nbconvert build step. You drop my-research.ipynb into content/research/ and Next.js automatically generates the static route and metadata.
  4. Full SEO & Table of Contents: Because headings and outputs are rendered into semantic HTML on the server, search engines index your notebooks and your existing TOC component can track section headings.

Understanding the .ipynb File Format

At its core, a Jupyter Notebook (.ipynb, nbformat v4) is a standard JSON file with three main top-level keys:

{
  "metadata": {
    "kernelspec": { "display_name": "Python 3", "language": "python" },
    "language_info": { "name": "python", "version": "3.11.8" }
  },
  "nbformat": 4,
  "nbformat_minor": 5,
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": ["# Section Heading\n", "Some explanation with $E = mc^2$."]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {},
      "source": ["import numpy as np\n", "np.arange(5)"],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 1,
          "data": {
            "text/plain": ["array([0, 1, 2, 3, 4])"]
          }
        }
      ]
    }
  ]
}

Key quirks to handle when parsing .ipynb JSON:

  • source can be string or string[]: Depending on the editor (VS Code, JupyterLab, Colab), cell.source and output.text may be stored either as an array of line strings or a single string. Always normalize with Array.isArray(s) ? s.join("") : String(s).
  • Four Output Types: Code cells can produce:
    1. stream (stdout or stderr console logs)
    2. execute_result (return value of the last expression in a cell, labeled Out [n]:)
    3. display_data (rich plots from matplotlib, seaborn, or IPython.display)
    4. error (Python exception name ename, message evalue, and ANSI-colored traceback)
  • Rich MIME Bundles: Inside execute_result and display_data, output.data is a dictionary keyed by MIME type (image/png, image/svg+xml, text/html, application/json, text/plain). You should render the richest visual representation (e.g., image/png plot or text/html Pandas DataFrame) and fall back to text/plain only when no rich visual exists.

Step-by-Step Implementation

1. Install Dependencies

We use the unified / remark / rehype ecosystem alongside shiki (via rehype-pretty-code) and katex (via rehype-katex):

bun add unified remark-parse remark-gfm remark-math remark-rehype \
  rehype-slug rehype-katex rehype-pretty-code rehype-stringify \
  shiki katex gray-matter

Make sure to import the KaTeX stylesheet in your root app/layout.tsx so mathematical formulas render properly:

import "./globals.css";
import "katex/dist/katex.min.css";

2. Build the Server-Side .ipynb Parser

Create src/lib/ipynb.ts to read .ipynb files from disk, extract metadata (supporting YAML frontmatter in the first Markdown cell, notebook JSON metadata, or automatic fallback from the first # Heading), and compile Markdown and Code cells into HTML:

import fs from "fs";
import path from "path";
import matter from "gray-matter";
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import remarkRehype from "remark-rehype";
import rehypeSlug from "rehype-slug";
import rehypeKatex from "rehype-katex";
import rehypePrettyCode from "rehype-pretty-code";
import rehypeStringify from "rehype-stringify";
 
const RESEARCH_DIR = path.join(process.cwd(), "content", "research");
 
function joinSource(source: string | string[] | undefined): string {
  if (!source) return "";
  return Array.isArray(source) ? source.join("") : String(source);
}
 
// Strip ANSI escape codes from terminal logs and Python tracebacks
function stripAnsi(str: string): string {
  return str.replace(
    /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
    "",
  );
}
 
async function renderMarkdownToHtml(markdown: string): Promise<string> {
  const file = await unified()
    .use(remarkParse)
    .use(remarkGfm as any)
    .use(remarkMath)
    .use(remarkRehype, { allowDangerousHtml: true })
    .use(rehypeSlug)
    .use(rehypeKatex)
    .use(rehypePrettyCode, {
      theme: {
        dark: "vitesse-dark",
        light: "vitesse-light",
      },
      onVisitLine(node: any) {
        if (node.children.length === 0) {
          node.children = [{ type: "text", value: " " }];
        }
      },
    })
    .use(rehypeStringify, { allowDangerousHtml: true })
    .process(markdown);
 
  return String(file);
}
 
async function renderCodeToHtml(
  code: string,
  language: string,
): Promise<string> {
  const fenced = `\`\`\`${language}\n${code.replace(/\n$/, "")}\n\`\`\``;
  return renderMarkdownToHtml(fenced);
}

Normalizing Cell Outputs

For each code cell, we map its outputs array into a clean serializable structure for our React component:

function parseOutput(output: any) {
  if (output.output_type === "stream") {
    return {
      outputType: "stream",
      streamName: output.name || "stdout",
      text: stripAnsi(joinSource(output.text)),
    };
  }
 
  if (output.output_type === "error") {
    return {
      outputType: "error",
      ename: output.ename || "Error",
      evalue: output.evalue || "",
      traceback: (output.traceback || []).map(stripAnsi).join("\n"),
    };
  }
 
  const data = output.data || {};
  return {
    outputType: output.output_type,
    executionCount: output.execution_count ?? null,
    svg: data["image/svg+xml"] ? joinSource(data["image/svg+xml"]) : undefined,
    imageMime: data["image/png"]
      ? "image/png"
      : data["image/jpeg"]
        ? "image/jpeg"
        : undefined,
    imageData:
      (joinSource(data["image/png"] || data["image/jpeg"]) || "").trim() ||
      undefined,
    html: data["text/html"] ? joinSource(data["text/html"]) : undefined,
    json: data["application/json"]
      ? JSON.stringify(data["application/json"], null, 2)
      : undefined,
    text: data["text/plain"]
      ? stripAnsi(joinSource(data["text/plain"]))
      : undefined,
  };
}

3. Build the Interactive "<NotebookRenderer />" Component

On the client side, src/components/NotebookRenderer.tsx receives the pre-highlighted cells and provides interactive controls:

  • A global Hide code / Show code button in the notebook header bar
  • Per-cell collapse toggles (In [1]:) and one-click Copy code buttons
  • Styled containers for stdout/stderr, Pandas HTML tables, Base64 plots (data:image/png;base64,...), and Python tracebacks
"use client";
 
import React, { useState } from "react";
import {
  Check,
  Copy,
  ChevronDown,
  ChevronRight,
  Eye,
  EyeOff,
  Terminal,
} from "lucide-react";
import { cn } from "@/lib/utils";
import type { RenderedNotebookCell, RenderedNotebookOutput } from "@/lib/ipynb";
 
export default function NotebookRenderer({
  cells,
  kernelName = "Python 3",
}: {
  cells: RenderedNotebookCell[];
  kernelName?: string;
}) {
  const [showAllCode, setShowAllCode] = useState(true);
  const codeCellsCount = cells.filter((c) => c.cellType === "code").length;
  const markdownCellsCount = cells.filter(
    (c) => c.cellType === "markdown",
  ).length;
 
  return (
    <div className="space-y-4">
      {/* Notebook Header Bar */}
      <div className="flex flex-wrap items-center justify-between gap-2 pb-4 mb-6 border-b border-border/60 text-xs text-muted-foreground/70">
        <div className="flex items-center gap-3 font-mono">
          <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md border border-border bg-muted/30 text-foreground/80">
            <Terminal className="h-3 w-3" />
            {kernelName}
          </span>
          <span>
            {markdownCellsCount} markdown &middot; {codeCellsCount} code cells
          </span>
        </div>
 
        {codeCellsCount > 0 && (
          <button
            onClick={() => setShowAllCode((prev) => !prev)}
            className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md border border-border/70 bg-muted/20 hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors font-mono text-xs"
          >
            {showAllCode ? (
              <EyeOff className="h-3.5 w-3.5" />
            ) : (
              <Eye className="h-3.5 w-3.5" />
            )}
            <span>{showAllCode ? "Hide code" : "Show code"}</span>
          </button>
        )}
      </div>
 
      {/* Render Markdown & Code Cells */}
      {cells.map((cell) =>
        cell.cellType === "markdown" ? (
          <div
            key={cell.id}
            className="notebook-markdown"
            dangerouslySetInnerHTML={{ __html: cell.renderedHtml }}
          />
        ) : (
          <CodeCellView
            key={cell.id}
            cell={cell}
            globalShowCode={showAllCode}
          />
        ),
      )}
    </div>
  );
}

Rendering Base64 Plots & Pandas DataFrames

Inside NotebookOutputView, Base64 images and Pandas HTML tables are rendered cleanly without duplicating the fallback text/plain representation:

{
  output.imageData && output.imageMime && (
    <div className="rounded-lg border border-border/60 bg-white dark:bg-[#121212] p-4 flex justify-center overflow-x-auto">
      <img
        src={`data:${output.imageMime};base64,${output.imageData}`}
        alt="Notebook output plot"
        className="max-w-full h-auto rounded"
      />
    </div>
  );
}
 
{
  output.html && (
    <div
      className="my-2 w-full overflow-x-auto rounded-lg border border-border/60 bg-[#FAFBFB] dark:bg-[#121212] p-3 [&_table]:w-full [&_table]:border-collapse [&_th]:px-3 [&_th]:py-2 [&_td]:px-3 [&_td]:py-1.5 [&_style]:hidden"
      dangerouslySetInnerHTML={{ __html: output.html }}
    />
  );
}

Notice [&_style]:hidden on the HTML output container—Pandas injects a <style scoped> tag inside DataFrame HTML exports with hardcoded borders. Hiding that inline style tag lets your Tailwind table classes style the DataFrame cleanly in both dark and light mode.

4. Wire Up the Next.js Dynamic Route

Finally, in src/app/diary/research/[slug]/page.tsx, we pre-generate static routes via generateStaticParams(), compute the Table of Contents from the aggregated Markdown cells (post.rawMarkdownForToc), and render <NotebookRenderer />:

import { notFound } from "next/navigation";
import NotebookRenderer from "@/components/NotebookRenderer";
import { TableOfContents } from "@/components/MagicToc";
import { getTableOfContents } from "@/lib/toc";
import { getAllResearchItems, getResearchBySlug } from "@/lib/ipynb";
import { formatDate } from "@/lib/utils";
 
export async function generateStaticParams() {
  const posts = await getAllResearchItems();
  return posts.map((post) => ({ slug: post.slugAsParams }));
}
 
export default async function PostPage({
  params,
}: {
  params: { slug: string };
}) {
  const post = await getResearchBySlug(params.slug);
  if (!post) notFound();
 
  const toc = await getTableOfContents(post.rawMarkdownForToc);
 
  return (
    <article className="relative">
      <TableOfContents toc={toc} />
      <div className="space-y-2 mb-12">
        <h1 className="text-4xl font-extrabold tracking-tight">{post.title}</h1>
        <time
          dateTime={post.publishedAt}
          className="block text-muted-foreground/60"
        >
          {formatDate(post.publishedAt)} &middot; {post.duration}
        </time>
      </div>
 
      {post.cells && (
        <NotebookRenderer
          cells={post.cells}
          language={post.language}
          kernelName={post.kernelName}
        />
      )}
    </article>
  );
}

Adding Metadata to Your .ipynb Files

With this setup, you have two ways to control how a notebook appears in the list view:

  1. Zero-Config (Automatic): Drop any .ipynb file into content/research/. The parser automatically uses the first # Heading as the title, the first paragraph as the summary, the file's modification date as publishedAt, and calculates reading time (duration) from the word count.
  2. Explicit YAML Frontmatter (Optional): Add a YAML frontmatter block at the top of the first Markdown cell in your notebook:
---
title: Principal Component Analysis from Scratch
publishedAt: 2026-11-09
summary: Deriving eigendecomposition and SVD for dimensionality reduction.
duration: 12min
---

The parser extracts the frontmatter metadata and strips it from the rendered cell automatically.