Here's a quick tip - React Router v7 routes aren't limited to just rendering UI components. They can work as API endpoints by returning various types of responses, making them true resource routes. Creating JSON Endpoints Here's a simple example of how to make your route return a JSON response: // app/routes/home.tsx export function loader() { return new Response(JSON.stringify([{ id: 1, title: "lorem ipsum" }]), { status: 200, headers: { "Content-Type": "application/json" }, }); } Let's break down what's happening here: new Response() creates a standard web Response object JSON.stringify() converts our JavaScript object to a JSON string The headers object sets Content-Type to application/json to tell clients what type of data to expect You're not limited to JSON responses only - you can use any valid MIME type. Beside loaders, you can also leverage actions for handling different HTTP methods beyond GET requests. Want to dive deeper? Check out the official guide dedicated to this topic. Thanks for reading!
Here's a quick tip - React Router v7 routes aren't limited to just rendering UI components. They can work as API endpoints by returning various types of responses, making them true resource routes.
Creating JSON Endpoints
Here's a simple example of how to make your route return a JSON response:
// app/routes/home.tsx
export function loader() {
return new Response(JSON.stringify([{ id: 1, title: "lorem ipsum" }]), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
Let's break down what's happening here:
-
new Response()
creates a standard webResponse
object -
JSON.stringify()
converts our JavaScript object to a JSON string - The headers object sets
Content-Type
toapplication/json
to tell clients what type of data to expect
You're not limited to JSON responses only - you can use any valid MIME type. Beside loaders, you can also leverage actions for handling different HTTP methods beyond GET
requests.
Want to dive deeper? Check out the official guide dedicated to this topic.
Thanks for reading!