Bridging the Gap: Integrating Laravel REST APIs with Remix
Overview
Modern web development often requires a clean separation between the data layer and the presentation layer. Connecting
Prerequisites
To follow this guide, you should have a solid grasp of
Key Libraries & Tools
- Axios: A promise-based HTTP client used to perform requests to the API.
- dotenv: Loads configuration variables from a
.envfile. - Tailwind CSS: A utility-first CSS framework for rapid UI development.
- Laravel Sanctum: Provides the token-based authentication system on the backend.
Code Walkthrough
Configuring the Server-Side Axios Instance
Create services/axios.server.js to centralize your API requests. This ensures every request uses the correct base URL and handles errors globally.
import axios from "axios";
const api = axios.create({
baseURL: process.env.API_HOST,
headers: {
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
},
});
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
throw redirect("/login");
}
return Promise.reject(error);
}
);
export default api;
Secure Session Management
Instead of storing tokens in localStorage, we use encrypted cookies. This mitigates Cross-Site Scripting (XSS) risks. In services/oauth.server.js, we initialize the cookie storage.
import { createCookieSessionStorage } from "@remix-run/node";
export const storage = createCookieSessionStorage({
cookie: {
name: "_session",
secure: process.env.NODE_ENV === "production",
secrets: [process.env.SESSION_SECRET],
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30,
httpOnly: true,
},
});
Syntax Notes
Remix uses loaders for GET requests and actions for mutations. By throwing a redirect() object within an interceptor, you can halt the execution flow and force the browser to a new URL, a pattern that simplifies authentication checks across multiple routes.
Practical Examples
This architecture is ideal for high-security applications like dashboards or booking systems. By fetching data in the loader,
Tips & Gotchas
Always include the Accept: application/json header. Without it, httpOnly cookies cannot be accessed by client-side scripts, so all token logic must reside in your server-side files.
