From one image to a web-ready GLB with the Meshy API

A short TypeScript script that turns one image into a GLB with the Meshy API, then inspects it, compresses it and loads it in three.js without surprises.

The fastest way to get a usable 3D asset out of Meshy is not the web app. It is the API, a short TypeScript script, and a check on what actually came back before anything goes near a scene. This post walks through that loop: one image in, one GLB out, inspected, slimmed down and loaded in three.js.

I use AI 3D generation as a starting point, not a finish line. The rule in my own pipeline is simple: a locked 2D concept goes in, a base mesh comes out, and a person decides whether that mesh is close enough to keep working on. The script below is the "base mesh comes out" part, written so it is boring and repeatable.

What you need

  • Node 20 or newer, so `fetch` is built in.
  • A paid plan, because API keys are not available on the free tier. The quickstart says so up front, and the Playground uses a built-in test key instead.
  • One clean input image. A single object, plain background, even lighting, the whole thing in frame.
  • About ten minutes, most of it waiting on the task.

The input image matters more than any parameter. A three-quarter view with a cluttered background will give you a three-quarter object fused to whatever was behind it. If you would not hand the image to a human modeler as a reference, do not hand it to a model either.

Keep the key out of the script

Create the key in the Developer Platform and copy it once. You cannot see it again after you leave that screen. Put it in an environment variable and nowhere else:

export MESHY_API_KEY="your-key-here"

If you run this from CI later, it goes in the secret store, not in the workflow file. I wrote about the logging side of that in [keeping GitHub Actions secrets out of the log](/journal/keep-github-actions-secrets-out-of-the-log).

Create the task

The Image to 3D endpoint takes either a public image URL or a base64 data URI. A data URI is handy for local files, since you do not have to host the image anywhere first. The response is just a task id. The actual work runs in the background.

// meshy-image-to-glb.ts
import { readFile, writeFile } from "node:fs/promises";
import { extname } from "node:path";

const API = "https://api.meshy.ai/openapi/v1/image-to-3d";
const key = process.env.MESHY_API_KEY;
if (!key) throw new Error("Set MESHY_API_KEY first");

const headers = {
  Authorization: `Bearer ${key}`,
  "Content-Type": "application/json",
};

async function toDataUri(path: string): Promise<string> {
  const ext = extname(path).slice(1).toLowerCase();
  const mime = ext === "jpg" ? "jpeg" : ext; // png, jpeg or webp
  const bytes = await readFile(path);
  return `data:image/${mime};base64,${bytes.toString("base64")}`;
}

async function createTask(imagePath: string): Promise<string> {
  const res = await fetch(API, {
    method: "POST",
    headers,
    body: JSON.stringify({
      image_url: await toDataUri(imagePath),
      ai_model: "latest",
      should_texture: true,
      enable_pbr: true,
      should_remesh: true,
      topology: "triangle",
      target_polycount: 30000,
      target_formats: ["glb"],
      origin_at: "bottom",
    }),
  });
  if (!res.ok) throw new Error(`Create failed: ${res.status} ${await res.text()}`);
  const { result } = (await res.json()) as { result: string };
  return result;
}

A few of those fields are worth explaining, because the defaults are not always what a web game wants.

  • `target_formats: ["glb"]` asks for only the format you will use. Leave it out and you get GLB, OBJ, FBX, STL and USDZ, which takes longer and gives you four files to ignore.
  • `should_remesh` with `target_polycount` decimates the result to roughly that face count. The docs list a range of 100 to 300,000 for remeshing, with 30,000 as the default. For a browser prop I start lower than that and raise it only if the silhouette falls apart.
  • `enable_pbr` adds metallic, roughness and normal maps on top of base color. That is what three.js's standard material expects, so it is usually worth it.
  • `origin_at: "bottom"` puts the pivot at the feet. You want that for anything that stands on a floor.

If you are making a low-poly game asset on purpose, the docs point you at the Smart Topology models (`model_type: "smart-topology"` with `meshy-t2` or `meshy-t2.5`) instead of remeshing a high-detail mesh. Those generate at the face count you ask for rather than cutting down afterward. Also note the deprecation banner at the top of the docs: `meshy-7` as a generation model retires on December 31, 2026. Use `latest` or `meshy-7.1` and you will not get surprised in January.

Poll politely

The task usually takes a few minutes. You poll the same endpoint with the task id until the status is `SUCCEEDED`, `FAILED` or `CANCELED`. The API sends a `Retry-After` header, so use it instead of hammering the endpoint every second.

type Task = {
  id: string;
  status: "PENDING" | "IN_PROGRESS" | "SUCCEEDED" | "FAILED" | "CANCELED";
  progress: number;
  model_urls?: { glb?: string };
  thumbnail_url?: string;
  task_error?: { message?: string } | null;
};

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

async function waitForTask(id: string, maxMinutes = 30): Promise<Task> {
  const deadline = Date.now() + maxMinutes * 60_000;
  while (true) {
    const res = await fetch(`${API}/${id}`, { headers });
    if (!res.ok) throw new Error(`Status check failed: ${res.status}`);
    const task = (await res.json()) as Task;
    if (["SUCCEEDED", "FAILED", "CANCELED"].includes(task.status)) return task;
    if (Date.now() > deadline) {
      throw new Error(`Task ${id} still ${task.status}. Check it later; do not start a new one.`);
    }
    console.log(`${task.status} ${task.progress}%`);
    const wait = Number(res.headers.get("retry-after")) || 5;
    await sleep(wait * 1000);
  }
}

That error message on timeout is the most important line in the file. When a task is slow, the tempting move is to run the script again. That starts a second paid task while the first one is still working. Save the id, check it later, and only create a new task when the old one has actually failed.

Download it before it expires

The GLB link in `model_urls` is a signed URL that only works for a while, and on every plan except Enterprise the files are kept for three days. Download the file right away and keep your own copy. Treat the hosted copy as a delivery slot, not storage.

async function main() {
  const imagePath = process.argv[2];
  if (!imagePath) throw new Error("Usage: tsx meshy-image-to-glb.ts ./concept.png");

  const id = await createTask(imagePath);
  console.log(`Task ${id} created`);
  await writeFile(`${id}.task.txt`, id); // so a rerun can resume, not duplicate

  const task = await waitForTask(id);
  if (task.status !== "SUCCEEDED" || !task.model_urls?.glb) {
    throw new Error(`Task ${task.status}: ${task.task_error?.message ?? "no GLB returned"}`);
  }

  const glb = await fetch(task.model_urls.glb);
  if (!glb.ok) throw new Error(`Download failed: ${glb.status}`);
  await writeFile("model.glb", Buffer.from(await glb.arrayBuffer()));
  console.log("Saved model.glb");
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

Run it with `npx tsx meshy-image-to-glb.ts ./concept.png`. If you would rather not poll at all, the API also supports streaming task updates and webhooks. For a one-off script, polling is simpler to reason about.

Look at what came back

This is the step people skip. A generated mesh can look fine in a thumbnail and still be wrong for a game: too many triangles, four 2K textures on a coin, or a scale that makes it the size of a building. I check every file with glTF Transform before it goes anywhere:

npx @gltf-transform/cli inspect model.glb

That prints the scene, meshes with vertex and triangle counts, materials, and every texture with its size and format. You are looking for three things:

1. Triangle count in the range you asked for. If it is far off, the remesh did not do what you think. 2. Texture sizes that make sense for how big the object will be on screen. 3. One material, not a pile of duplicates.

Then open it in Blender and look at it from the side you did not give the model. AI 3D is good at the side it was shown and guesses at the rest. The back of a character, the underside of a prop and anything thin, like straps, ears or antennas, are where the guessing shows. If the asset has to match a locked 2D design, compare it at the same angle as the concept, not from the angle that looks best.

Make it small enough for the web

The raw GLB is usually heavier than it needs to be. glTF Transform's optimize command handles the common wins in one pass:

npx @gltf-transform/cli optimize model.glb model.web.glb \
  --compress meshopt \
  --texture-compress webp \
  --texture-size 1024

Meshopt compresses the geometry, WebP shrinks the textures, and `--texture-size` caps them at 1024 pixels. For a prop that fills a tenth of the screen, 1024 is plenty. Run `inspect` again on the output and compare. I covered the Blender export side of this in [Blender glTF settings that matter for the web](/journal/blender-gltf-settings-that-matter-for-the-web), and the same rules apply here: fewer materials, sensible texture sizes and a pivot that is where you expect it.

Load it in three.js

Because the file is now meshopt-compressed, the loader needs the decoder. Everything else is the standard GLTFLoader setup:

import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { MeshoptDecoder } from "three/addons/libs/meshopt_decoder.module.js";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 1.2, 3);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 2));

const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);

loader.load("/models/model.web.glb", (gltf) => {
  const model = gltf.scene;
  // Normalize height to 1 unit so every generated asset lands at a known scale
  const size = new THREE.Box3().setFromObject(model).getSize(new THREE.Vector3());
  model.scale.setScalar(1 / size.y);
  scene.add(model);
});

renderer.setAnimationLoop(() => renderer.render(scene, camera));

The scale line is there because generated models do not share a unit. One comes back a meter tall, the next one is a few centimeters. Normalizing on load keeps a test scene honest. In a real project, fix the scale once in Blender and drop the line. The API also has an `auto_size` option that estimates a real-world height, which is worth trying if you have a lot of props.

What I would tell myself before the first run

  • The image is the prompt. Spend the time there, not on parameters.
  • Ask for one format and a target face count. Defaults are tuned for a general audience, not for a browser game.
  • Never rerun a slow task. Save the id and resume.
  • Download within the retention window and keep your own copy.
  • Inspect before you trust. A thumbnail is not a review.
  • Treat the result as a base mesh. Cleanup, rigging and the final look are still a person's job.

None of this is complicated. It is just easy to skip when the thumbnail looks good, and that is exactly when it bites.

Some links in this post are referral links.

Back to Journal