DEV Community

Rafał Goławski
Rafał Goławski

Posted on

2 1 1

🗃️ Resource Routes in React Router v7

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" },
  });
}
Enter fullscreen mode Exit fullscreen mode

Let's break down what's happening here:

  1. new Response() creates a standard web Response object
  2. JSON.stringify() converts our JavaScript object to a JSON string
  3. 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!

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (1)

Collapse
 
best_codes profile image
Best Codes

This is very interesting, thanks for sharing!
I think I will use this in my in-development framework.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay