Vibe coding with Claude Code course ยท Module 5: Reddit clone

Crew parchments: Markdown in posts without smuggled scripts

9 min read ยท
In this lesson9

Polly wants to list the voyage supplies as bullet points in her post and Redbeard wants to make the Kraken warning bold. The body field accepts only plain text, though, so their posts look like one long paragraph. The easiest way out is to let HTML into posts, but then any pirate could paste a script that runs in the whole crew's browsers. In this lesson Claude Code adds formatting with that door kept shut, and a test checks that it really is.

The problem: formatting without a back door

Markdown is a simple way to write formatting with ordinary characters. Hash signs at the start of a line make a heading, a hyphen makes a list item, two asterisks on each side make bold text, and square plus round brackets make a link. This is Polly's post:

## Voyage supplies

**Warning:** a Kraken was sighted near Mist Bay.

- barrel of water
- hardtack

[Port map](https://example.com/tortuga)

Bold text has three parts on one line: **, the text and ** again. You store such text like any other and turn it into headings and lists only when you display it. That is where the trap waits. Many libraries turn Markdown into ready-made HTML text that has to be inserted through dangerouslySetInnerHTML. You know the rule from lesson 3_3: you never display user content through dangerouslySetInnerHTML. So you need a tool that builds React elements from Markdown, not HTML text.

Request for Claude Code

You name the library in the request yourself, because this is a security decision, not a convenience one. According to its documentation, react-markdown is safe by default: it builds a tree of React elements, does not use dangerouslySetInnerHTML and does not run HTML from the content.

Request for Claude Code:

Add Markdown to Crew Council post bodies: headings, bold text, lists
and links. Users write the content, so render it with react-markdown,
without dangerouslySetInnerHTML and without raw HTML. One component,
components/PostBody.tsx, for the post card and the post page. Styles:
the prose class from @tailwindcss/typography (Tailwind 4, @plugin in
@app/globals.css). Tests first, in components/PostBody.test.tsx:
Markdown gives a heading, bold text and a list; the text <img src="x"
onerror="alert(1)"> does not create an image; a javascript: link loses
its address. Do not add any other packages. At the end run tests, lint
and build, and show the output.

The sentence about other packages is not decoration. Every package is someone else's code in your project, and Claude happily adds "while it is at it" code highlighting or HTML support.

What Claude did: two packages

Open the Source Control panel in Cursor and click package.json. One line was added to dependencies:

"dependencies": {
  "next": "16.4.6",
  "react": "19.3.0",
  "react-dom": "19.3.0",
  "react-markdown": "^10.1.0"
},

dependencies are the packages the app needs while running. The second package, "@tailwindcss/typography": "^0.5.20", went into devDependencies, because it is needed only when building styles (versions as of November 2026). The caret ^ lets npm install newer releases without breaking changes. There is no marked, rehype-raw or dompurify here: exactly the two packages you asked for. In app/globals.css a line was added under the Tailwind import:

@import "tailwindcss";
@plugin "@tailwindcss/typography";

@plugin is Tailwind 4's way of loading plugins. A tailwind.config.js file with require(...) is the Tailwind 3 way, which the plugin's documentation now describes only for older projects.

What Claude wrote: PostBody

Open components/PostBody.tsx:

import ReactMarkdown from "react-markdown";

export default function PostBody({ content }: { content: string }) {
  return (
    <div className="prose prose-sm max-w-none prose-a:text-blue-600">
      <ReactMarkdown>{content}</ReactMarkdown>
    </div>
  );
}

ReactMarkdown receives the post text as its child and returns plain React elements: h2, strong, ul, a. The classes sit on the wrapping div, because the current version of the library does not accept a className prop. prose gives headings their size and lists their bullets, prose-sm shrinks the text to card size, max-w-none removes the width limit that prose sets for comfortable reading, and prose-a:text-blue-600 colours only the links. The component has no "use client", so it works both on the post page and in the card inside Feed. The card and the post page now show the body through <PostBody content={post.content} />.

What Claude wrote: the test that guards the door

Open components/PostBody.test.tsx. render from Testing Library, which Claude installed in lesson 4_1, draws the component in a pretend browser, and container is the element where the result landed. Two cases guard security:

it("does not insert HTML from the post body", () => {
  const { container } = render(<PostBody content={'<img src="x" onerror="alert(1)">'} />);
  expect(container.querySelector("img")).toBeNull();
});

it("does not let a javascript: link through", () => {
  const { container } = render(<PostBody content="[map](javascript:alert(1))" />);
  expect(container.querySelector("a")?.getAttribute("href")).toBe("");
});

querySelector returns the first element matching a CSS selector, or null, and toBeNull expects that no such element exists. onerror is code the browser runs when an image fails to load, so a tag like that is enough for an attack. react-markdown shows it as plain text. A javascript: link runs code on click, so the library lets through only safe kinds of addresses, such as https and mailto, and turns the rest into an empty address. The first test in the file checks the formatting itself: a heading, bold text and two list items.

A test of the test

A test that always passes guards nothing. So we checked the version agents like to write: the marked library turns Markdown into HTML text, and the component inserts it through dangerouslySetInnerHTML. Here is the middle of the output:

 โฏ components/PostBody.test.tsx (3 tests | 2 failed)
     ร— does not insert HTML from the post body
     ร— does not let a javascript: link through

AssertionError: expected <img src="x" onerror="alert(1)"></img> to be null

      Tests  2 failed | 22 passed (24)

The formatting test passed, because everything looked fine on screen. Two security tests failed: the image with onerror landed on the page, and the link kept its javascript: address. The marked documentation itself warns that the library does not sanitize its output and tells you to run it through a separate package. The hole was invisible to the eye, and the test showed it in a second.

An editor with a live preview

A pirate wants to see the effect before publishing a post. Second request: "In @components/CreatePostForm.tsx show a live preview next to the body field through PostBody. On a phone, put the preview under the field". In the form the body field and the preview now stand in a grid:

<div className="grid gap-2 md:grid-cols-2">
  <textarea
    value={content}
    onChange={(event) => setContent(event.target.value)}
    rows={6}
    placeholder="Body in Markdown: **bold**, - list, [link](https://...)"
    aria-label="Post body"
    className="w-full rounded border border-gray-300 p-2 font-mono text-sm"
  />
  <section aria-label="Post preview" className="rounded border border-dashed border-gray-300 p-2">
    {content.trim() ? (
      <PostBody content={content} />
    ) : (
      <p className="text-sm text-gray-400">Your post preview will appear here.</p>
    )}
  </section>
</div>

One content state feeds both the field and the preview, so every character instantly changes the formatted post next to it. md:grid-cols-2 puts them side by side from medium screens up, and on a phone the preview lands under the field. The preview uses the same PostBody as the card, so the pirate sees exactly what the crew will see. Nothing is saved until they click Publish.

Captain's review

  1. The door shut in the browser. Run npm run dev and type <img src=x onerror=alert(1)> and [map](javascript:alert(1)) into the body field. The preview shows the tag as text, and the link "map" has no address. No dialog may pop up.
  2. Zero hits. Search the whole project in Cursor for dangerouslySetInnerHTML. You expect zero hits.
  3. Packages under the magnifying glass. A typical agent mistake is rehype-raw, added "so that HTML works in posts". That plugin switches on HTML from the content, and the react-markdown documentation meant it for content you trust, and for safety advises adding rehype-sanitize. On a forum the whole crew writes, HTML is not needed, so you reject such a change.
  4. The styles work. Publish Polly's post from the start of the lesson through the form. The heading should be larger than the text and the list should have bullets. When everything looks like one grey paragraph, the @plugin line is missing or Claude wrote a Tailwind 3 configuration. When the agent moves the classes to <ReactMarkdown className="prose">, npm run build stops it with an error: Property 'className' does not exist.

Next step

When tests, lint and build are green, ask for a commit, for example "Markdown in posts: PostBody, preview, security tests". Then a small step in the same loop:

Add strikethrough (~~text~~) and tables from GitHub Flavored Markdown
through the remark-gfm plugin. Test first in @components/PostBody.test.tsx:
"~~old course~~ new course" gives a del element with the text "old course".
Run the tests and show the output, then stop before writing code.

The test will fail with expected undefined to be 'old course', because without the plugin the tildes stay plain text. If the evening is ending, leave it red and leave the session with /exit. A red test is the best bookmark in the logbook: tomorrow you know right away where you stopped. The security tests will run together with it, so the plugin will not quietly open the door. In the editor below waits a small editor with a preview that builds React elements instead of HTML: insert the attack attempt and see that it stays as text.

Remember: on the crew's parchment everyone writes in their own ink, but the captain presses the seal, and the test checks that nobody swapped it.

Code for this lesson: App.jsx
// Crew parchments: Markdown turned into React elements, never into HTML text
import { useState } from 'react';

// Like react-markdown's default: only safe kinds of addresses
const isSafeUrl = (url) => /^(https?:|mailto:|\/)/i.test(url);

// **bold** and [link](address) on one line
function renderInline(text, lineKey) {
  const parts = text.split(/(\*\*[^*]+\*\*|\[[^\]]+\]\([^)\s]+\))/g);
  return parts.map((part, i) => {
    const key = lineKey + '-' + i;
    const bold = part.match(/^\*\*([^*]+)\*\*$/);
    if (bold) return <strong key={key}>{bold[1]}</strong>;
    const link = part.match(/^\[([^\]]+)\]\(([^)\s]+)\)$/);
    if (link) {
      return (
        <a key={key} href={isSafeUrl(link[2]) ? link[2] : ''} className="text-blue-600 underline">
          {link[1]}
        </a>
      );
    }
    // Plain text: React shows it as a string, including <img ...> and <script>
    return part;
  });
}

// Headings (#, ##), lists (- ) and paragraphs
function renderMarkdown(markdown) {
  const blocks = [];
  let items = [];
  const closeList = () => {
    if (items.length > 0) {
      blocks.push(<ul key={'ul-' + blocks.length} className="ml-5 list-disc space-y-1">{items}</ul>);
      items = [];
    }
  };
  markdown.split('\n').forEach((line, i) => {
    if (line.startsWith('- ')) {
      items.push(<li key={i}>{renderInline(line.slice(2), i)}</li>);
      return;
    }
    closeList();
    if (line.startsWith('## ')) blocks.push(<h3 key={i} className="text-lg font-bold">{renderInline(line.slice(3), i)}</h3>);
    else if (line.startsWith('# ')) blocks.push(<h2 key={i} className="text-xl font-bold">{renderInline(line.slice(2), i)}</h2>);
    else if (line.trim()) blocks.push(<p key={i}>{renderInline(line, i)}</p>);
  });
  closeList();
  return blocks;
}

const startText = `## Voyage supplies

**Warning:** a Kraken was sighted near Mist Bay.

- barrel of water
- hardtack

[Port map](https://example.com/tortuga)`;

const attack = '\n\n<img src=x onerror=alert(1)> [click](javascript:alert(1))';

export default function App() {
  const [content, setContent] = useState(startText);

  return (
    <div className="min-h-screen bg-gray-100 p-4 text-gray-900">
      <div className="mx-auto max-w-3xl space-y-3">
        <h1 className="text-2xl font-bold">New post in Crew Council</h1>
        <div className="grid gap-3 md:grid-cols-2">
          <textarea
            value={content}
            onChange={(event) => setContent(event.target.value)}
            rows={12}
            aria-label="Post body"
            className="w-full rounded border border-gray-300 bg-white p-2 font-mono text-sm"
          />
          <section aria-label="Post preview" className="space-y-2 rounded border border-dashed border-gray-400 bg-white p-3">
            {content.trim() ? renderMarkdown(content) : <p className="text-gray-400">Your post preview will appear here.</p>}
          </section>
        </div>
        <button
          type="button"
          onClick={() => setContent((prev) => prev + attack)}
          className="rounded bg-red-700 px-3 py-1 text-white hover:bg-red-800"
        >
          Insert an attack attempt
        </button>
        <p className="text-sm text-gray-600">
          The img tag stays as text, and the javascript: link loses its address. The preview does not use dangerouslySetInnerHTML.
        </p>
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is Markdown in the context of forum posts?

  2. 2. Why does Crew Council render post bodies through react-markdown instead of marked and dangerouslySetInnerHTML?

Hands-on tasks in the game

  • Code editor

    Markdown editor with live preview

  • Horizontal ordering

    Arrange the notation for bold text in Markdown (one line, left to right):

  1. QuestionQuiz: What is Markdown
  2. Coding taskPractice: Markdown editor
  3. Put in orderSorting: Bold in Markdown
  4. QuestionQuiz: Markdown without dangerouslySetInnerHTML

Useful articles