Skip to content

agyaboat/lara-fetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

📦 lara-fetch

npm bundle size license

A tiny fetch wrapper that handles Laravel Sanctum CSRF like a boss.


⚡ Quick Features

  • ✅ Auto CSRF cookie fetch on write operations (POST / PUT / PATCH / DELETE)
  • ✅ Reads XSRF-TOKEN cookie + injects matching header automatically
  • ✅ Built for Laravel Sanctum SPA authentication
  • ✅ Zero-config convenience for local development
  • ✅ Full configuration control for production
  • ✅ Per-request overrides (just a 3rd param)
  • GET / POST / PUT / PATCH / DELETE helper methods
  • ✅ Debug mode for console tracing
  • ✅ Lightweight
  • ✅ Browser (CDN) support via jsdeliver
  • ❌ Limitation: Not SSR-friendly yet

Small library. Main character energy. 😎


🚀 Install

npm install lara-fetch
# or
yarn add lara-fetch
# or
pnpm add lara-fetch

🧃 Basic Usage (Local Dev Quickstart)

✅ Assumes:

  • Laravel: http://localhost:8000
  • Sanctum CSRF route: /sanctum/csrf-cookie
  • Cookie name: XSRF-TOKEN

⚠️ Warning:
Only use this zero-config setup for local development.
Production requires proper configuration (next section ✅).


GET Example

import { laraFetch } from "lara-fetch";

const res = await laraFetch("/api/user");
const data = await res.json();

console.log(data);

POST Example

import { laraFetch } from "lara-fetch";
const res = await laraFetch("/login", {
  method: "POST",
  body: JSON.stringify({ email, password }),
});
const data = await res.json();
console.log(data);

🌍 Production Setup (Recommended)

Configure once globally:

import { laraFetch } from "lara-fetch";

laraFetch.configure({
  baseURL: "https://api.example.com",
  csrfPath: "/sanctum/csrf-cookie",
  credentials: "include",
  debug: false,
  defaultHeaders: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
});


//=============  OR =================== 
import { laraConfigure } from "lara-fetch";
laraConfigure({ ... });

Config options:

Option Purpose Default
baseURL Your Laravel API root http://localhost:8000
csrfPath Where Sanctum stores CSRF cookie /sanctum/csrf-cookie
xsrfCookieName Cookie name holding CSRF token XSRF-TOKEN
defaultHeaders Global headers for requests JSON headers
credentials Include cookies for Sanctum auth include
debug Enables console logs false

🎛️ Per-request Override

Switch host, headers, credentials just for one call:

await laraFetch(
  "/special",
  { method: "POST" },
  {
    baseURL: "https://staging.example.com",
    defaultHeaders: {
      "X-Feature-Flag": "Beta",
    },
    debug: true,
  }
);

💡 Only pass a third object parameter to laraFetch, including as many of the config options you want to override for this specific request.


HELPER Methods

Use dedicated methods for common HTTP verbs:
Available: get, post, put, patch, del

📜 NB:

No need to set method in options, these helpers do it for you.

import { laraFetch } from "lara-fetch";
// GET
const res1 = await laraFetch.get("/api/user"); 

// POST
const res2 = await laraFetch.post("/login", {
  body: JSON.stringify({ email, password }),
});

// PUT
const res3 = await laraFetch.put("/api/user/1", {
  body: JSON.stringify({ name: "New Name" }),
});

// PATCH
const res4 = await laraFetch.patch("/api/user/1", {
  body: JSON.stringify({ name: "Updated Name" }),
});

// DELETE
const res5 = await laraFetch.del("/api/user/1");

✅ What helper methods do under the hood

laraFetch Method HTTP Verb Sent Body Auto-Modified? Behavior / Why
get() GET Normal GET, nothing special
post() POST ✅ (if form) _method=POST Safe for Laravel form submits (even tho POST rarely needs spoofing)
put() PUT or POST _method=PUT if form, else real PUT Laravel treats PUT over form as POST + spoof
patch() PATCH or POST _method=PATCH if form, else real PATCH Same reason as PUT
del() DELETE or POST _method=DELETE if form, else real DELETE Delete forms always need spoof in Laravel

🤖 Built-in auto detection

Body Format What laraFetch does
JSON (application/json) Use real HTTP verbs (PUT/PATCH/DELETE)
FormData Convert request to POST + inject _method=<verb>
x-www-form-urlencoded Same as FormData override ✅
No body Normal request Behavior

✅ TL;DR: Defaults in one line

If it's JSON → send real method. If its a form → spoof method with POST.


🐛 Debugging

Enable debug mode globally or per-request to see console logs:

laraConfigure({ debug: true }); // Global
// or
await laraFetch("/endpoint", {}, { debug: true }); // Per-request

🌍 Browser Support via CDN

lara-fetch can be used directly in the browser — no build tools needed!

CDN Example:

<script src="https://cdn.jsdelivr.net/npm/lara-fetch@1.0.3/dist/index.umd.js"></script>
<script>
  // Configure once
  laraFetch.configure({
    baseURL: 'https://jsonplaceholder.typicode.com',
    debug: true
  });

  // Fetch example
  laraFetch.get('users/3')
    .then(res => res.json())
    .then(console.log)
    .catch(console.error);
</script>

✅ Works out of the box in browsers ✅ Same API as Node/Vite builds ✅ Ideal for quick prototyping or Laravel SPA setups



🔐 Manual CSRF (Optional)

Pre-fetch the CSRF cookie if needed:

import { laraFetch } from "lara-fetch";
await laraFetch.getCsrfToken();

//================= OR ===================
import { laraCsrf } from "lara-fetch";

await laraCsrf();
// Now safe to make write requests

💡 You can override baseURL, csrfPath, or any other config by passing an object to laraCsrf:

await laraFetch.getCsrfToken({...override_configs});

//================= OR ===================
await laraCsrf({...override_configs});

🧠 TypeScript Support

Type definitions are included. Example:

import type { LaraConfig } from "lara-fetch";

laraConfigure({
  baseURL: "https://prod.example.com",
} satisfies LaraConfig);

Autocomplete + type safety ✅ Dev confidence: 💯



⚠️ Limitations:

  • Built strictly for SPAs powered by Laravel API backends.
  • Not SSR-friendly yet - currently working on universal support for server-side environments.


License

MIT License © Agyemang Bright Boateng (Agya Boat) Go Build stuff.



Contribute

Contributions welcome! Feel free to open issues or PRs on GitHub.

About

A tiny fetch helper that makes Laravel API calls just work.

Resources

Stars

Watchers

Forks

Packages

No packages published