Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Blog with an Admin Area

Build a blog with Remix and React Router: cacheable public pages, SEO meta tags, an admin area behind a role check, draft and publish, a sitemap and a streamed comments section.

The notes app was private. A blog is the opposite: most visitors are anonymous, the pages should be fast, cacheable and indexable, and only one or two people may write. That changes the design. This project combines public cacheable routes, SEO meta tags, an admin area guarded by a role, draft and publish states, a sitemap and a streamed comments section. As before, the real code is shown read-only and a runnable model checks the rules.

Routes and responsibilities

URL Audience Notes
/ and /blog everyone list of published posts, cacheable
/blog/:slug everyone one post, cacheable, 404 for drafts
/sitemap.xml crawlers resource route returning XML
/admin editors layout with role check, private, no-store
/admin/posts/new, /admin/posts/:id editors create, edit, publish
/login editors as in Login and Logout

A resource route is a route module with a loader but no default component; it returns any Response, such as XML, JSON or an image.

Public post page

TSX
// app/routes/blog.$slug.tsx (read-only)
import { data } from "react-router";
import { Suspense } from "react";
import { Await } from "react-router";
import type { Route } from "./+types/blog.$slug";

export async function loader({ params }: Route.LoaderArgs) {
  const post = await getPublishedPost(params.slug);
  if (!post) throw data("Post not found", { status: 404 });  // drafts look like missing pages

  return data(
    { post, comments: getComments(post.id) },                // comments streamed, not awaited
    { headers: { "Cache-Control": "public, max-age=60, s-maxage=3600, stale-while-revalidate=86400" } }
  );
}

export function meta({ data }: Route.MetaArgs) {
  if (!data) return [{ title: "Post not found" }];
  return [
    { title: `${data.post.title} | My Blog` },
    { name: "description", content: data.post.summary },
    { property: "og:title", content: data.post.title },
    { tagName: "link", rel: "canonical", href: `https://example.com/blog/${data.post.slug}` },
  ];
}

export default function Post({ loaderData }: Route.ComponentProps) {
  return (
    <article>
      <h1>{loaderData.post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: loaderData.post.html }} />
      <Suspense fallback={<p>Loading comments...</p>}>
        <Await resolve={loaderData.comments}>{(list) => <Comments items={list} />}</Await>
      </Suspense>
    </article>
  );
}

Design decisions worth repeating:

  • The Markdown is converted to HTML on the server at save time (sanitized there), so the browser receives HTML, not a Markdown library. Rendering with dangerouslySetInnerHTML is safe only because the HTML was sanitized.
  • The post is awaited because it decides the status code and the <title>; the comments are streamed. See Streaming with Promises.
  • A draft returns the same 404 as a missing slug.
  • Cache headers follow HTTP Caching and Headers. When an editor publishes, purge that URL and the list page from the CDN.

Sitemap as a resource route

TypeScript
// app/routes/sitemap[.]xml.ts (read-only)
export async function loader() {
  const posts = await listPublishedPosts();
  const urls = posts.map((p) => `<url><loc>https://example.com/blog/${p.slug}</loc><lastmod>${p.updatedAt.toISOString().slice(0, 10)}</lastmod></url>`).join("");
  return new Response(
    `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls}</urlset>`,
    { headers: { "Content-Type": "application/xml", "Cache-Control": "public, s-maxage=3600" } }
  );
}

The admin area

TSX
// app/routes/admin.tsx (read-only)
export async function loader({ request }: Route.LoaderArgs) {
  const user = await requireRole(request, ["editor", "admin"]);
  return data({ user }, { headers: { "Cache-Control": "private, no-store" } });
}

// app/routes/admin.posts.$id.tsx (read-only)
export async function action({ request, params }: Route.ActionArgs) {
  await requireRole(request, ["editor", "admin"]);          // check again in every action
  const form = await request.formData();
  const intent = form.get("intent");

  if (intent === "publish") {
    await publishPost(params.id);
    await purgeCdn([`/blog/${await slugOf(params.id)}`, "/blog"]);
    return redirect("/admin");
  }
  // otherwise save a draft ...
}

The role helper and the 403 behavior come from Protecting Routes. Note that the admin check is repeated in the action; a layout loader alone does not protect it.

Model the rules

This runnable model covers three rules that are easy to get wrong: drafts are invisible to the public, public responses carry cache headers while admin ones are private, and only editors can publish.

Node.js Stand-in: publish rules, headers and the sitemap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Extras for a real blog

  • RSS/Atom feed as another resource route.
  • Pagination with ?page=2 in the list loader, canonical links without duplicate parameters.
  • Comments posted by a fetcher with rate limiting from CSRF and Security and server-side moderation.
  • Images: store originals, serve resized WebP/AVIF with explicit dimensions to avoid layout shifts (Bundle Size and Performance).
  • Structured data (JSON-LD Article) emitted through meta.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a resource route?

    Resource routes serve non-HTML responses like sitemaps, feeds and downloads.
  2. 2. Why does an unpublished draft return the same 404 as a missing slug?

    Different answers would confirm that a record exists. Treat inaccessible and missing the same.
  3. 3. Why must the admin role check be repeated inside every admin action?

    Each action is an HTTP endpoint and must authorize itself.
  4. 4. Which Cache-Control fits the admin area?

    Pages for signed-in users must never be stored by shared caches.

Summary

  • Public pages: await what shapes the status and title, stream the rest, cache at the CDN, set meta tags.
  • Treat drafts as missing for the public; purge the CDN on publish.
  • Admin pages: role checks in loaders and actions, private, no-store.
  • Resource routes serve the sitemap and feeds.

Next: Practice Exercises