Sub topic 19
Resource routes for APIs and files
A resource route is a route module that sends back a raw HTTP response instead of rendering a page. Use one for a JSON endpoint, a CSV download, an image, an RSS feed, or a webhook receiver.
This chapter assumes you have read the chapters on route configuration, loaders, and actions. It also assumes you know HTTP methods, status codes, and the Response and Headers classes. The examples reuse the ~/contacts.server module from earlier chapters. They also assume it exports a getContacts() function that returns an array of contacts.
What makes a route a resource route
A resource route is a route module with no default export. React Router never renders a component for it, so there is no HTML document, no layout, and no root Layout wrapper. The module's loader handles GET and HEAD requests. Its action handles POST, PUT, PATCH, and DELETE.
Whatever the function returns goes straight back to the client. If you return a plain object, React Router serializes it for its own data requests. A resource route is called by arbitrary clients, so return a real Response and control the headers yourself.
Registering the route
Register a resource route in app/routes.ts like any other route. The file extension on the URL is part of the path you choose, so name it what the client expects.
import {
type RouteConfig,
index,
route,
} from "@react-router/dev/routes";
export default [
index("routes/home.tsx"),
route("api/contacts", "routes/api/contacts.ts"),
route("api/contacts/:contactId", "routes/api/contact.ts"),
route("contacts.csv", "routes/contacts-csv.ts"),
] satisfies RouteConfig;The files end in .ts, not .tsx, because they contain no JSX.
A JSON endpoint
A loader answers reads and an action answers writes. Route types are generated for resource routes too, so params stays typed.
import type { Route } from "./+types/contact";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
return Response.json({ error: "Not found" }, { status: 404 });
}
return Response.json(contact, {
headers: { "Cache-Control": "private, max-age=30" },
});
}For writes, read the body yourself and return an explicit status. The action is called for every non-GET method, so reject the ones you do not support.
import type { Route } from "./+types/contacts";
import { createContact } from "~/contacts.server";
export async function action({ request }: Route.ActionArgs) {
if (request.method !== "POST") {
return new Response(null, {
status: 405,
headers: { Allow: "POST" },
});
}
let body: unknown;
try {
body = await request.json();
} catch {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
const name =
typeof body === "object" && body !== null && "name" in body
? String((body as { name: unknown }).name).trim()
: "";
if (!name) {
return Response.json({ error: "Name is required" }, { status: 400 });
}
const contact = await createContact({ name });
return Response.json(contact, {
status: 201,
headers: { Location: `/api/contacts/${contact.id}` },
});
}Validate input here just as you would in a page action. A resource route is a public entry point, and nothing upstream has checked the body.
Serving a file
For downloads, set Content-Type and Content-Disposition. This example builds a CSV export.
import { getContacts } from "~/contacts.server";
function csvCell(value: string): string {
return `"${value.replaceAll('"', '""')}"`;
}
export async function loader() {
const contacts = await getContacts();
const rows = contacts.map((c) => [csvCell(String(c.id)), csvCell(c.name)].join(","));
const csv = ["id,name", ...rows].join("\r\n");
return new Response(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="contacts.csv"',
},
});
}The same pattern works for binary data. Pass a ReadableStream or a Buffer as the body and set the matching Content-Type. Streaming a large file avoids holding all of it in memory.
Linking to a resource route
A normal Link does client-side navigation. It asks React Router for page data, not for your file. To reach a resource route from the UI, force a full browser request.
import { Link } from "react-router";
export function ExportLinks() {
return (
<>
<a href="/contacts.csv" download>Download CSV</a>
<Link to="/contacts.csv" reloadDocument>Download CSV</Link>
</>
);
}Both links work. reloadDocument makes Link behave like a plain anchor. A Form has the same prop for posting to a resource route. For calling a JSON endpoint from client code, use fetch directly. A useFetcher can also target a resource route with fetcher.load or fetcher.submit, which is useful when you want React Router to track pending state.
Edge cases
- Returning a component by accident. If you add a default export, the route becomes a page route and clients get HTML.
- Authentication. Resource routes do not inherit parent loaders. Check the session in each one and return
401or403. Do not redirect an API client to a login page. - CORS. Browsers on other origins need
Access-Control-Allow-Originheaders. HandleOPTIONSrequests inside theaction, becauseOPTIONSis not aGET. - CSRF. Cookie-authenticated
POSTendpoints are open to cross-site requests. UseSameSite=Laxcookies, as in the session chapter, and check theOriginheader for state-changing calls. - Prerendering. Resource routes can be prerendered when listed in
prerender, producing a static file. That fits an RSS feed, not an endpoint that depends on the request. - SPA mode. With
ssr: falsethere is no server to run the route, so resource routes with server loaders are not available.
Exercise
You add routes/contacts-csv.ts with a loader that returns a CSV Response. A <Link to="/contacts.csv"> in your page shows an error instead of downloading the file. What is wrong, and how do you fix it?
Show answer
Link does client-side navigation and requests route data, not the raw file. Add reloadDocument to the Link, or use a plain <a href="/contacts.csv" download>, so the browser makes a full request to the resource route.
Exercise
A resource route exports only an action. A client sends GET /api/contacts. What does it receive, and which export would you add to support it?
Show answer
There is no loader to handle GET, so React Router responds with an error status (405 Method Not Allowed). Add a loader export that returns the list as Response.json(...).