Build a Christmas Card Background Generator with the Image API
Use Node.js and the Nbility Image API to generate a Christmas card background, persist its async task, resume polling or downloads, and add accurate lettering afterward.

A small Christmas card generator can start with one image API request: generate a background with space for a message, save the asynchronous task ID, and add names and greetings in a layout tool afterward. Keeping the illustration and lettering separate makes revisions easier and leaves a task to resume if the script stops.
This guide provides a local command-line example for Node.js 22 or later. It submits an image task once, polls for completion, and saves a PNG, JPEG, or WebP file. It is a starting point for a seasonal app, rather than a website or public service.
The Nbility image documentation and task response implementation were checked on December 1, 2026. The script passed syntax checks and offline tests with simulated responses. It was not used with a live API key to measure image quality, generation time, or cost. For creative preparation, start with the Christmas photo and reference guide.
What does this generator produce?
The example turns a text prompt into an asynchronous image task and then a local background file. You add the final greeting with a design tool.
The request is fixed to one 1536x1024 landscape image at medium quality. Its prompt places a tree and ornaments on the right, leaves the left half clear, and asks for no lettering. Set IMAGE_MODEL to a GPT Image model available to your current account and group. Check models and pricing first; a model appearing in the catalog does not make it available to every group.
Keeping these choices fixed makes the first version easy to follow. If you later expose size or quantity controls, offer a bounded set of supported choices and show their cost before generation.
X-New-Api-Async-Task and /v1/images/tasks/:task_id are Nbility's asynchronous interface. The code requests response_format: "url" under the Nbility Image API contract. If you change providers, check the new contract instead of assuming that changing the hostname is sufficient.
What do you need before running it?
Use Node.js 22 or later, a valid Nbility API key, and an image model your account can call. No SDK or additional package is required.
Create a private local file named .env.card. Replace the placeholders with your configuration and keep the file out of Git:
NBILITY_API_KEY=YOUR_API_KEY
IMAGE_MODEL=YOUR_AVAILABLE_IMAGE_MODEL
On macOS or Linux, set restrictive permissions:
chmod 600 .env.card
umask 077
The API key stays in the local process environment. A future web version should make model requests from your own server; do not move the key into browser code or a frontend build variable.
How do you submit a task and resume it?
Save the code below as card.mjs. Give every job its own directory and run only one process per directory. The script records a submission before sending the POST. If its response is lost, rerunning the command will not silently create another generation.
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
import { resolve, join } from 'node:path';
const api = 'https://api.nbility.ai/v1';
const key = process.env.NBILITY_API_KEY;
const dir = resolve(process.argv[2] || 'card-job');
const record = join(dir, 'task.json');
if (!key) throw new Error('Set NBILITY_API_KEY first.');
await mkdir(dir, { recursive: true, mode: 0o700 });
let state;
try {
state = JSON.parse(await readFile(record, 'utf8'));
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const save = async () => {
await writeFile(`${record}.tmp`, JSON.stringify(state), { mode: 0o600 });
await rename(`${record}.tmp`, record);
};
const call = async (path, options = {}) => {
const response = await fetch(`${api}${path}`, {
...options,
headers: { Authorization: `Bearer ${key}`, ...options.headers },
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`API HTTP ${response.status}; check the saved job.`);
const body = await response.json();
if (body.code !== 'success') throw new Error('API did not return success.');
return { data: body.data, retry: Number(response.headers.get('Retry-After')) };
};
if (!state) {
const model = process.env.IMAGE_MODEL;
if (!model) throw new Error('Set IMAGE_MODEL to an available image model.');
state = { phase: 'submitting', model, startedAt: new Date().toISOString() };
await save();
// A lost POST response must not cause another generation POST.
const { data } = await call('/images/generations', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-New-Api-Async-Task': 'true' },
body: JSON.stringify({
model, n: 1, size: '1536x1024', quality: 'medium', response_format: 'url',
prompt: 'A Christmas greeting card background, warm ivory paper, a small fir tree and copper ornaments on the right third, soft natural light, left half empty for a personal message, no lettering, no logo, no watermark.',
}),
});
if (typeof data?.task_id !== 'string' || !data.task_id) {
throw new Error('No task_id received. Inspect the original request; do not resubmit.');
}
state.taskId = data.task_id;
state.phase = 'accepted';
await save();
}
if (!state.taskId) throw new Error('Submission is uncertain. Check logs or contact support.');
if (state.phase === 'failed') throw new Error('This task failed. Inspect it before a new job.');
const deadline = Date.now() + 10 * 60_000;
while (!state.url && Date.now() < deadline) {
const { data, retry } = await call(`/images/tasks/${encodeURIComponent(state.taskId)}`);
if (data?.status === 'failed') {
state.phase = 'failed';
await save();
throw new Error('Image task failed. Inspect its details in the console.');
}
if (data?.status === 'succeeded') {
state.url = data.image_urls?.[0] || data.result_url;
if (typeof state.url !== 'string' || !state.url) throw new Error('Succeeded without an image URL.');
state.phase = 'succeeded';
await save();
break;
}
if (!['submitted', 'queued', 'in_progress'].includes(data?.status)) {
throw new Error('Unrecognized task state. Inspect the saved task.');
}
await new Promise(done => setTimeout(done, Math.min(30, Math.max(3, retry || 3)) * 1000));
}
if (!state.url) throw new Error('Local wait ended. Run the same command to resume this task.');
if (new URL(state.url).protocol !== 'https:') throw new Error('Expected an HTTPS result URL.');
// No API Authorization header is sent to the image host.
const image = await fetch(state.url, { signal: AbortSignal.timeout(60_000) });
if (!image.ok) throw new Error(`Download HTTP ${image.status}; rerun this job to retry download.`);
const bytes = Buffer.from(await image.arrayBuffer());
const extension = bytes.subarray(0, 8).toString('hex') === '89504e470d0a1a0a' ? 'png'
: bytes.subarray(0, 3).toString('hex') === 'ffd8ff' ? 'jpg'
: bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP' ? 'webp' : null;
if (!extension) throw new Error('Expected PNG, JPEG, or WebP. Inspect the response.');
const output = join(dir, `card.${extension}`);
await writeFile(`${output}.part`, bytes, { mode: 0o600 });
await rename(`${output}.part`, output);
console.log(`Saved ${output}. Open it to verify the image before adding text.`);
Run it with:
node --env-file=.env.card card.mjs card-job
A completed download is written as card-job/card.png, card.jpg, or card.webp, based on its file signature. Saved ... confirms that bytes were saved. The code checks the signature, not a full image decode: open the file and inspect the composition and empty area before adding text.
The fetch and AbortSignal.timeout APIs are documented in Node.js 22. The script's 30-second API request timeout, 60-second download timeout, and 10-minute polling window are local example settings, not service completion guarantees. Ending that polling window does not cancel the server-side task.
What happens when a step fails?
Run the same command again to read task.json and continue from its existing state.
| Saved state | What the next run does | What to check |
|---|---|---|
| A task ID exists; generation is still pending | Polls the existing task | Use valid credentials for the same account |
| A result URL exists; download failed | Downloads that result again | The URL remains accessible and the network works |
| Submission returned no task ID | Stops without another POST | Inspect the original request in the console or contact support |
| The task failed | Stops | Inspect the failure before deciding on a new job |
| Download is not a supported bitmap | Stops without writing a finished file | Check its format or whether it is an error page |
Keep task.json private because its result URL may contain access parameters. Neither the example nor this article promises permanent task or URL retention. Save finished images into storage you manage when you need them long term.
Use a new directory, such as card-job-02, only when you deliberately want a new image. Do not create a new directory to bypass an uncertain submission: the original request may already have been accepted. See image download and task recovery for the wider recovery process.
How do you finish the card?
Import the background into a layout tool, add a short checked greeting, and export for its intended destination. Verify names, years, dates, and promotional details as text.
The prompt leaves the left half clear for a message such as Merry Christmas and With love, Alex. A New Year version can use Happy New Year 2027. Once the typography and spacing are settled, changing a name does not require another image generation. The Christmas card design guide covers layout and delivery choices in more detail.
Check task completion, file readability, spelling, and the card's appearance after actual delivery separately. A successful API response cannot verify the rest of that workflow.
To develop a larger app, keep one working job as a reproducible example, record its real parameters and result, and then add a page, task list, and the usage controls your product needs. The SDK quickstart provides a connection reference. This local script implements the image-generation path; accounts, spending controls, and operating a public product require their own implementation.


