Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Root and Entry Files

Understand root.tsx, Layout, Links, Meta, Scripts and the optional entry.client and entry.server files in React Router v7 framework mode, with runnable stand-ins.

Every page in a Remix app is wrapped by one special route: the root route in app/root.tsx. It renders the <html> document, so it is where you put the <head>, the global styles, the page chrome and the app-wide error screen. Two more files, entry.client.tsx and entry.server.tsx, control how React is started in the browser and on the server. This lesson explains all three.

root.tsx in full

Here is the root module that the default template ships (slightly shortened). It is real code, so it is read-only.

TSX
// app/root.tsx
import {
  isRouteErrorResponse,
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from "react-router";
import type { Route } from "./+types/root";
import "./app.css";

export const links: Route.LinksFunction = () => [
  { rel: "preconnect", href: "https://fonts.googleapis.com" },
];

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}

export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  let message = "Oops!";
  let details = "An unexpected error occurred.";
  if (isRouteErrorResponse(error)) {
    message = error.status === 404 ? "404" : "Error";
    details = error.status === 404 ? "Page not found." : error.statusText;
  }
  return (
    <main>
      <h1>{message}</h1>
      <p>{details}</p>
    </main>
  );
}

The pieces, one by one

Piece What it does
Layout wraps the app, the error boundary and the hydrate fallback in one HTML shell, so the document is always valid
<Meta /> renders the <title> and <meta> tags collected from the meta export of every matched route
<Links /> renders <link> tags from the links exports of every matched route (stylesheets, preloads, icons)
<Scripts /> renders the <script> tags that load the client bundle. Leave it out and the page stays plain HTML
<ScrollRestoration /> restores scroll position when users go back and forward
<Outlet /> renders the matched child route
ErrorBoundary shown when anything below throws; it receives the thrown value as error

Pay attention to the order inside <body>: the content first, then ScrollRestoration and Scripts. Placing <Meta /> and <Links /> in <head> lets the framework put route-specific tags in the right place.

Why a Layout export?

The root default export is just a component, but errors and the loading fallback also need an <html> shell. If each rendered its own, you would repeat the markup. A Layout export is used around all three, so the document structure lives in one place. In older Remix apps you will see the shell directly inside the default export instead.

Styles

A plain import "./app.css" works in route modules because Vite handles it; the CSS is collected for the matched routes. The links export with rel: "stylesheet" and a ?url import is the other documented way:

TSX
import stylesheet from "./app.css?url";

export const links: Route.LinksFunction = () => [
  { rel: "stylesheet", href: stylesheet },
];

Stand-in: building the document from route exports

The framework collects meta and links from every matched route, root first. This stand-in imitates that merging. Later routes override earlier ones for title, which is how a product page replaces the site name with its own.

JS Stand-in: merge meta and links from matched routes

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

No output.

Only one <title> comes out, the deepest one, and the stylesheet and preload from different routes are both present. Real Remix does the same job with a stricter rule: the last route that defines a title or a tag with the same name wins. A route can also read the parent's tags through matches in its meta function. See links, navigation and meta for the real API.

entry.client.tsx

This file starts React in the browser. The built-in default is equivalent to:

TSX
// app/entry.client.tsx
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";

startTransition(() => {
  hydrateRoot(
    document,
    <StrictMode>
      <HydratedRouter />
    </StrictMode>,
  );
});

Note that React hydrates the whole document, which is why the root route renders <html>. Reveal the file with npx react-router reveal when you need to add error reporting, an analytics provider or a different hydrateRoot option.

entry.server.tsx

This file turns a request into a response. The default uses streaming rendering, so the browser starts receiving HTML before slow data finishes:

TSX
// app/entry.server.tsx (simplified)
import { renderToPipeableStream } from "react-dom/server";
import { ServerRouter, type EntryContext } from "react-router";
import { PassThrough } from "node:stream";
import { createReadableStreamFromReadable } from "@react-router/node";

export default function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  routerContext: EntryContext,
) {
  return new Promise((resolve, reject) => {
    const { pipe } = renderToPipeableStream(
      <ServerRouter context={routerContext} url={request.url} />,
      {
        onShellReady() {
          responseHeaders.set("Content-Type", "text/html");
          const body = new PassThrough();
          resolve(
            new Response(createReadableStreamFromReadable(body), {
              headers: responseHeaders,
              status: responseStatusCode,
            }),
          );
          pipe(body);
        },
        onShellError: reject,
      },
    );
  });
}

It also may export handleError(error, { request }), a good place to log server errors, and handleDataRequest to touch the responses of loader requests.

Stand-in: an entry.server handler

The next stand-in keeps just the contract: it receives the request, a status code and headers, then returns a Response. It adds a security header and an X-Request-Id, which are typical customisations for the real file.

JS Stand-in: handleRequest adds headers and logs errors

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

No output.

Practical tips

  • Keep root.tsx light. Anything heavy slows every page.
  • Put the language on <html lang>; screen readers and search engines use it.
  • Do not read window while rendering Layout: it runs on the server too.
  • Root loaders are fine (for example, to read the user for a navigation bar) but they run on every request, so keep them quick. See loaders.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if you remove <Scripts /> from the root Layout?

    Scripts emits the script tags for the client bundle. Without it the page is static HTML (forms and links still work as normal browser navigation).
  2. 2. Which export lets root.tsx define the HTML shell used for the app, the error boundary and the loading fallback?

    Layout wraps all three, so the document markup is not repeated.
  3. 3. How do you copy the default entry files into your project?

    react-router reveal copies entry.client.tsx and entry.server.tsx so you can customise them.
  4. 4. Where is a good place to log server errors for every request?

    handleError receives the error and the request for anything thrown while handling a request.

Summary

  • root.tsx renders the document: Meta, Links, Outlet, ScrollRestoration and Scripts in a Layout.
  • meta and links exports from every matched route are merged into the head; deeper routes win.
  • entry.client.tsx hydrates the document; entry.server.tsx turns a request into a streamed response.
  • Both entry files have defaults; reveal them only when customising.
  • The root ErrorBoundary is the last line of defence for uncaught errors.

Next: Web Fundamentals in Remix