Resource Routes

Resource Routes are not part of your application UI, but are still part of your application. They can send any kind of Response.

Most routes in Remix are UI Routes, or routes that actually render a component. But routes don’t always have to render components. There are a handful of cases where you want to use route as a general-purpose endpoint to your website. Here are a few examples:

  • JSON API for a mobile app that reuses server-side code with the Remix UI
  • Dynamically generating PDFs
  • Dynamically generating social images for blog posts or other pages
  • Webhooks for other services like Stripe or GitHub
  • a CSS file that dynamically renders custom properties for a user’s preferred theme

Creating Resource Routes

If a route doesn’t export a default component, it can be used as a Resource Route. If called with GET, the loader’s response is returned and none of the parent route loaders are called either (because those are needed for the UI, but this is not the UI). If called with POST, the action’s response is called.

For example, consider a UI Route that renders a report, note the link:

  1. export async function loader({ params }: LoaderArgs) {
  2. return json(await getReport(params.id));
  3. }
  4. export default function Report() {
  5. const report = useLoaderData<typeof loader>();
  6. return (
  7. <div>
  8. <h1>{report.name}</h1>
  9. <Link to="pdf" reloadDocument>
  10. View as PDF
  11. </Link>
  12. {/* ... */}
  13. </div>
  14. );
  15. }

It’s linking to a PDF version of the page. To make this work we can create a Resource Route below it. Notice that it has no component: that makes it a Resource Route.

  1. export async function loader({ params }: LoaderArgs) {
  2. const report = await getReport(params.id);
  3. const pdf = await generateReportPDF(report);
  4. return new Response(pdf, {
  5. status: 200,
  6. headers: {
  7. "Content-Type": "application/pdf",
  8. },
  9. });
  10. }

When the user clicks the link from the UI route, they will navigate to the PDF.

Linking to Resource Routes

It’s imperative that you use reloadDocument on any Links to Resource Routes

There’s a subtle detail to be aware of when linking to resource routes. You need to link to it with <Link reloadDocument> or a plain <a href>. If you link to it with a normal <Link to="pdf"> without reloadDocument, then the resource route will be treated as a UI route. Remix will try to get the data with fetch and render the component. Don’t sweat it too much, you’ll get a helpful error message if you make this mistake.

URL Escaping

You’ll probably want to add a file extension to your resource routes. This is tricky because one of Remix’s route file naming conventions is that . becomes / so you can nest the URL without nesting the UI.

To add a . to a route’s path, use the [] escape characters. Our PDF route file name would change like so:

  1. # original
  2. # /reports/123/pdf
  3. app/routes/reports/$id/pdf.ts
  4. # with a file extension
  5. # /reports/123.pdf
  6. app/routes/reports/$id[.pdf].ts
  7. # or like this, the resulting URL is the same
  8. app/routes/reports/$id[.]pdf.ts

Handling different request methods

To handle GET requests export a loader function:

  1. import type { LoaderArgs } from "@remix-run/node"; // or cloudflare/deno
  2. import { json } from "@remix-run/node"; // or cloudflare/deno
  3. export const loader = async ({ request }: LoaderArgs) => {
  4. // handle "GET" request
  5. return json({ success: true }, 200);
  6. };

To handle POST, PUT, PATCH or DELETE requests export an action function:

  1. import type { ActionArgs } from "@remix-run/node"; // or cloudflare/deno
  2. export const action = async ({ request }: ActionArgs) => {
  3. switch (request.method) {
  4. case "POST": {
  5. /* handle "POST" */
  6. }
  7. case "PUT": {
  8. /* handle "PUT" */
  9. }
  10. case "PATCH": {
  11. /* handle "PATCH" */
  12. }
  13. case "DELETE": {
  14. /* handle "DELETE" */
  15. }
  16. }
  17. };

Webhooks

Resource routes can be used to handle webhooks. For example, you can create a webhook that receives notifications from GitHub when a new commit is pushed to a repository:

  1. import crypto from "crypto";
  2. import type { ActionArgs } from "@remix-run/node"; // or cloudflare/deno
  3. import { json } from "@remix-run/node"; // or cloudflare/deno
  4. export const action = async ({ request }: ActionArgs) => {
  5. if (request.method !== "POST") {
  6. return json({ message: "Method not allowed" }, 405);
  7. }
  8. const payload = await request.json();
  9. /* Validate the webhook */
  10. const signature = request.headers.get(
  11. "X-Hub-Signature-256"
  12. );
  13. const generatedSignature = `sha256=${crypto
  14. .createHmac("sha256", process.env.GITHUB_WEBHOOK_SECRET)
  15. .update(JSON.stringify(payload))
  16. .digest("hex")}`;
  17. if (signature !== generatedSignature) {
  18. return json({ message: "Signature mismatch" }, 401);
  19. }
  20. /* process the webhook (e.g. enqueue a background job) */
  21. return json({ success: true }, 200);
  22. };