shlogg · Early preview
Rafał Goławski @rgolawski

Unlocking React Router V7: Routes As API Endpoints With JSON Responses

React Router v7 routes aren't just for UI components! They can return JSON responses or any valid MIME type, making them true resource routes. Use `new Response()` and `JSON.stringify()` to create API endpoints.

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...