Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 72 ยท Routing

Templates and Other Special Files

Learn the rest of the App Router file conventions: template.tsx versus layout, default.tsx, route.ts, favicon and icon files, Open Graph images, robots and sitemap.

By now you know the main special files: page.tsx for the UI, layout.tsx for shared structure, and the three fallback files from the last lesson. The App Router has a few more, and they are easy to confuse because some look alike. template.tsx seems to be a layout but behaves differently. route.ts seems to be a page but returns data. And a handful of files such as icon.png or sitemap.ts do not render components at all; they generate things search engines and browsers ask for.

This lesson is a tour. For each file you will see what it does, where it goes, and the mistake that usually goes with it. The real framework cannot run on this site, so Next.js code is shown read-only. Two runnable stand-ins show the behavior that is hard to picture from text: how a template re-mounts while a layout does not, and how a file name is turned into a URL and a head tag.

Files that wrap or fill in

template.tsx Like a layout, but fresh on every navigation.
default.tsx Fallback for a parallel slot with no match.
1 / 3

template.tsx: a layout that starts over

A layout wraps its children and stays mounted while the user moves between child routes. That is great for a sidebar, but sometimes you want the opposite: a wrapper that is created fresh every time the URL below it changes. That is a template.tsx.

TSX
// app/blog/template.tsx (read-only)
export default function Template({ children }: { children: React.ReactNode }) {
  return <div className="fade-in">{children}</div>;
}

A template receives children like a layout, and when both exist the template sits inside the layout and wraps the page. The difference is what happens on navigation:

  • A layout keeps its state and does not re-render when you move between its child pages.
  • A template gets a new instance for each child segment. State inside it resets, useEffect runs again, and DOM it created is rebuilt.

Reach for a template when you need an entry animation for each page, when an effect must run per navigation (such as logging a page view), or when you want a form or an uncontrolled input to reset. For everything else, a layout is cheaper and keeps the user's state, so prefer it.

The stand-in below plays both roles. The "layout" and the "template" each hold a counter and a mount note. Click through the links and watch which counter survives. The key on the template is the stand-in for Next.js giving it a new instance for each segment.

Layout versus template

Press each counter a few times, then switch pages. The layout counter keeps its value and its mount count stays at 1; the template counter returns to 0 and its mount count grows. Keep in mind that this is a model: Next.js performs the same re-mounting for you based on the navigation, you never write the key yourself.

default.tsx: the fallback for parallel slots

You met default.tsx in Parallel and Intercepting Routes. The short version: a parallel slot such as @analytics renders next to your page. When a user navigates inside the app, Next.js remembers what each slot showed. But on a full page load of a URL the slot has no match for, it needs something to render, and without a default.tsx you get a 404. So the file is simply the "nothing matched" view for that slot.

TSX
// app/dashboard/@analytics/default.tsx (read-only)
export default function Default() {
  return null; // render nothing when this slot has no page for the URL
}

Returning null is the most common choice. Return real UI when the slot should show a default panel instead.

route.ts: an endpoint instead of a page

A route.ts file turns a folder into an HTTP endpoint. Instead of exporting a component, you export functions named after HTTP methods.

TypeScript
// app/api/health/route.ts (read-only)
export async function GET() {
  return Response.json({ status: "ok" });
}

The two rules to remember: a folder cannot have both a page.tsx and a route.ts (they would claim the same URL), and route.ts files live anywhere in app/, not only under app/api. They are covered in depth in Route Handlers.

Metadata files: names become head tags

Some files exist so you can skip writing metadata by hand. Drop a file with the right name into app/ and Next.js generates the matching <link> or <meta> tag. A nested folder overrides the file from its parent for that part of the site.

File name What it produces
favicon.ico The classic tab icon (only at the root of app/)
icon.png, icon.svg, icon.ico <link rel="icon">
apple-icon.png <link rel="apple-touch-icon"> for iOS home screens
opengraph-image.png <meta property="og:image"> for link previews
twitter-image.png The card image for X (Twitter)
robots.txt The crawler rules file at /robots.txt
sitemap.xml The sitemap at /sitemap.xml
manifest.json The web app manifest for installable sites

Images can also be generated by code. Name the file icon.tsx or opengraph-image.tsx, export the image size and content type, and return an ImageResponse. Next.js renders it to a PNG on the server.

TSX
// app/blog/[slug]/opengraph-image.tsx (read-only)
import { ImageResponse } from "next/og";

export const size = { width: 1200, height: 630 };
export const contentType = "image/png";
export const alt = "Blog post preview";

export default async function Image({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  return new ImageResponse(
    <div style={{ fontSize: 72, display: "flex", padding: 80 }}>{slug}</div>,
    size
  );
}

robots and sitemap have a code version too. They are normal default exports that return data, and Next.js turns the result into the right text format.

TypeScript
// app/sitemap.ts (read-only)
import type { MetadataRoute } from "next";

export default function sitemap(): MetadataRoute.Sitemap {
  return [
    { url: "https://example.com/", lastModified: new Date() },
    { url: "https://example.com/blog" },
  ];
}
TypeScript
// app/robots.ts (read-only)
import type { MetadataRoute } from "next";

export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: "*", allow: "/", disallow: "/admin" },
    sitemap: "https://example.com/sitemap.xml",
  };
}

Metadata and SEO goes deeper into the metadata object, titles and Open Graph.

Trying it: a file name becomes a URL and a tag

The stand-in below is plain Node.js. It takes a list of file names from an app/ folder, applies the conventions above, and prints what each file turns into. This is a model of the lookup, not the real implementation (Next.js also adds a content hash to icon URLs so browsers can cache them for a long time).

Node.js Which file produces which tag?

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.

Look at how the nested app/blog/opengraph-image.png becomes a path under /blog, while the root ones stay at the top. That is the "nested folder overrides" rule in action: the closest file to the route wins.

Two mistakes to avoid

Putting a template where a layout belongs. Because a template remounts, every navigation tears down its state: a search box in a template empties itself, and a video player restarts. If you see state mysteriously vanish on navigation, check which file you used.

Forgetting that favicon.ico has a fixed home. favicon.ico must be in the root of app/. Other icon files can be nested, but the classic favicon cannot.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A page loses its input text every time the user navigates to a sibling route. What is the most likely cause?

    Templates create a new instance for each child segment, so their state resets. Layouts stay mounted and keep state.
  2. 2. Which pair of files cannot live in the same folder?

    Both page.tsx and route.ts would claim the same URL, one to render UI and one to answer HTTP methods, so Next.js does not allow them together.
  3. 3. What does a default.tsx file in a parallel slot do?

    When the URL has no matching page inside the slot, default.tsx is the fallback; without it you get a 404.
  4. 4. How do you generate an Open Graph image from code?

    An opengraph-image.tsx file exports size and contentType and returns an ImageResponse from next/og, which Next.js renders as a PNG.

Summary

  • template.tsx wraps its children like a layout but re-mounts on every navigation, which resets state and re-runs effects.
  • default.tsx is the fallback for a parallel slot that has no match for the URL.
  • route.ts exports HTTP method functions and cannot share a folder with page.tsx.
  • Files such as favicon.ico, icon.*, apple-icon.*, opengraph-image.*, robots, sitemap and manifest become head tags or crawler files; code versions (.ts, .tsx) generate the same output.
  • The nearest metadata file to a route wins; only favicon.ico must stay in the root of app/.

Next: React Server Components