Create a custom HTTP endpoint
In this guide, you will learn how to create a custom HTTP endpoint.
Create a custom HTTP endpoint
Front-Commerce is built on the top of Remix, it means that you can create custom HTTP endpoint using the Standard Remix Routing System.
Routes without a default export won't serve any HTML content. You will have to
use loader
and
action
functions to perform
custom interaction with backend data.
Keep in mind that loader
is only used for GET
requests, while action
is
used for any other request type.
GET request example
Let's create a custom HTTP endpoint to serve a simple JSON response.
import { json } from "@front-commerce/remix/node";
export async function loader() {
return json({ message: "Hello, world!" });
}
When accessing this route, you will get a JSON response with the following content:
curl http://localhost:4000/api/hello
{
"message": "Hello, world!"
}
You can also use the standard Javascript Response object to send a response.
export async function loader() {
return new Response("Hello World!", {
status: 200,
headers: { "Content-Type": "text/plain" },
});
}
POST/PUT/PATCH/DELETE request example
For POST/PUT/PATCH/DELETE requests, you can use the action
function.
export async function action({ request }: ActionFunctionArgs) {
const method = request.method;
return new Response(`Hey ! You've made a ${method} request !`);
}
When acessing this route with a POST request, you will get a response with the following content:
curl -X POST http://localhost:4000/api/hello
Hey ! You've made a POST request !
Or with a PUT request:
curl -X PUT http://localhost:4000/api/hello
Hey ! You've made a PUT request !
You can leverage this endpoint to perform any custom interaction you need, here are some example of things you can do with these:
- Serve content from the filesystem.
import fs from "node:fs";
export async function loader() {
const file = fs.readFileSync("/home/server/myfile.pdf");
return new Response(file);
}
- Return computed data like time
import { json } from "@front-commerce/remix/node";
export async function loader() {
return json({ time: new Date().toISOString() });
}
- Serve data from a remote API
import { json } from "@front-commerce/remix/node";
export async function loader() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
return json(data);
}