October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Load Custom Blocks into GrapesJS with the grapesjs-tailwind Plugin

Load Laravel-returned blocks into GrapesJS by awaiting the endpoint response and registering each item with editor.Blocks.add(). Use Axios as a browser global or bundle it with Laravel Mix.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To load custom blocks from a Laravel endpoint into GrapesJS, fetch the endpoint asynchronously, wait for its JSON response, and register each block with editor.Blocks.add(). If your custom browser script uses Axios, load Axios as a browser global before that script or bundle it with Laravel Mix; plain browser scripts do not provide Node’s require() or automatically resolve bare import statements.

Why the original code fails

The reported errors come from mixing JavaScript environments and skipping an asynchronous step:

As an Amazon Associate I earn from qualifying purchases.

  • require('axios') is a CommonJS pattern for Node.js, not a function available in an ordinary browser script.
  • A bare import statement needs a module-aware script and a resolvable dependency, or a bundler. It cannot be pasted into a classic script and expected to work.
  • response.json() returns a Promise. Reading customBlocks before awaiting that Promise means you are reading from the Promise, not the parsed response object.
  • await must be inside an async function unless the script is a JavaScript module.

The browser-versus-Node distinction and asynchronous JSON parsing are also covered in the original SitePoint-related Stack Overflow discussion and the MDN Fetch API guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Load blocks with native Fetch

This example assumes the endpoint returns JSON shaped like {"customBlocks":[...]}. Confirm that response contract in your Laravel route/controller; the endpoint’s actual shape and any authentication requirements depend on your application.

async function loadBlocks(editor) {
  const response = await fetch('/pages/4/get-custom-blocks', {
    method: 'GET',
    credentials: 'same-origin',
    headers: { Accept: 'application/json' }
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  const payload = await response.json();
  const customBlocks = payload.customBlocks || [];

  customBlocks.forEach((block) => {
    editor.Blocks.add(block.id, {
      label: block.label,
      attributes: { class: block.class },
      content: block.content,
      category: {
        label: block.category,
        open: block.category === 'Blog'
      }
    });
  });
}

loadBlocks(editor).catch(console.error);

fetch() resolves to a Response, not the decoded JSON. Check response.ok for HTTP failures and await response.json() before using the payload. MDN notes that JSON parsing can itself fail if the body is not valid JSON. For a GET request, do not add a JSON request body unless your server specifically requires one; use query parameters in the URL where needed.

Choose how Axios reaches the browser

Load Axios as a browser global

If the existing custom file expects a global axios variable, ensure the Axios browser build is loaded before it. The Stack Overflow answer for this case adds https://unpkg.com/axios before js/custom-grapesjs-tailwind.min.js in the Laravel GrapesJS script list. The order matters: the dependency must run first.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Then the loader can use Axios while still awaiting the request:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function loadBlocksWithAxios(editor) {
  const { data } = await axios.get('/pages/4/get-custom-blocks', {
    headers: { Accept: 'application/json' }
  });

  (data.customBlocks || []).forEach((block) => {
    editor.Blocks.add(block.id, {
      label: block.label,
      attributes: { class: block.class },
      content: block.content,
      category: {
        label: block.category,
        open: block.category === 'Blog'
      }
    });
  });
}

loadBlocksWithAxios(editor).catch(console.error);

Use this global approach only when the Axios browser script is actually included ahead of the code that calls it. It avoids require() but does not make Node-style imports available.

Bundle Axios with Laravel Mix

If the project already builds front-end assets with Laravel Mix, import Axios in the Mix entry file and emit a browser bundle. The browser then loads the generated bundle rather than trying to resolve a bare import inside a classic script. This keeps dependency handling in the build step instead of relying on a separate global script.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Register returned items with GrapesJS

GrapesJS exposes its Block Manager as editor.Blocks. Call editor.Blocks.add(id, props) for each returned item, using a stable unique ID and properties such as label, content, category, and attributes. See the GrapesJS Block Manager API.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

The grapesjs-tailwind project documents browser CDN, npm, and Git distribution options. Whichever distribution you use, initialize GrapesJS and its plugin before calling the loader so that editor and its block manager exist. For example, the project’s browser usage initializes GrapesJS with plugins: ['grapesjs-tailwind'].

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check the endpoint contract and request context

  • Verify that the response is valid JSON and contains a customBlocks array. If the server returns an array directly or uses a different key, adjust the code to match it.
  • Ensure each item has the fields your registration code reads: id, label, class, content, and category. Adapt or validate fields if the application uses a different schema.
  • The Fetch example uses credentials: 'same-origin', appropriate when the same-origin request relies on browser session credentials. If the endpoint is protected, make sure the user is authorized and follow the application’s authentication and CSRF setup. A GET request ordinarily should not need a JSON body.
  • Keep the loader in an async function and attach error handling, as shown. This makes both request failures and invalid JSON visible instead of silently leaving the block list empty.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.