Developer Tutorials
Add timed subtitles to a video with Node.js and JSON
Run one small Node.js example to add three timed captions, track the render and download the finished MP4. The video, captions and code are included.
By Mina RamzyPublished Updated
Start with a video and three timed sentences. The supplied Node.js example checks the request, submits the render and downloads an eight-second MP4. It uses prepared captions; it does not generate a transcript.
The result you will make
Play the clips one at a time with sound. The second keeps the same footage and narration, with each sentence visible while it is spoken. The captions are burned into the picture, so viewers do not need to switch them on.
Both clips are 720 × 1280 and eight seconds long, with AI-generated narration. The after clip shows the result of running the example.
Run the example
You need Node.js 22 or newer with npm, a Zvid account with API access, and an API key. Get your key at app.zvid.io/api-keys. Run this on your computer or server, where the key can stay private.
Budget 8 render credits for the supplied clip. Validation is free. Keep at least that balance available, then check the current estimate before rendering. Your account must allow the sample’s duration and dimensions. The included script stops if the estimate exceeds 8 credits or validation returns warnings.
1. Download the matching files
Extract the ZIP. Open a terminal inside its json-subtitles folder, where package.json is located. Install the pinned dependency, the official @zvid/sdk package:
node --version
npm ci
If PowerShell blocks npm.ps1, use npm.cmd in place of npm in these commands. You do not need to change your execution policy.
The files have different jobs:
| File | What it contains |
|---|---|
| Source video | The hosted clip shown before subtitles, including its narration. Download it separately if needed. |
data/captions.json |
The three sentences and their start/end times. |
data/project.json |
The video URL, dimensions, duration and subtitle style. |
data/request.json |
The complete API request for the supplied example. |
src/index.js and src/helpers.js |
Validation, submission, job tracking and download code. |
The project already points to a working hosted copy of the supplied clip. You do not need to upload it. The script combines project.json and captions.json each time; request.json is a ready-made reference, not a second file you must edit.
You can also download the source video, timed captions, project JSON or complete request separately.
2. Set your API key
Copy .env.example to a new file named .env in the same folder. In PowerShell, run Copy-Item .env.example .env. In macOS or Linux Terminal, run cp .env.example .env.
Open .env in a text editor and paste your key after ZVID_API_KEY=. Keep the credit limit as shown:
ZVID_API_KEY=
MAX_RENDER_CREDITS=8
Do not add the key to the JSON files or commit .env. The SDK sends it in the x-api-key header to https://api.zvid.io. The video download does not receive your API key.
Optional detail: using API keys.
3. Validate, then render
First run the free check:
npm start
For the supplied example, expect Valid: true. Estimated credits: 8. followed by No render submitted. The complete validation response is saved in out/validation.json. If this check fails, fix the reported problem before continuing.
When the estimate is acceptable, start the paid render:
npm run render
The script validates again, submits once, prints the job ID and reports state changes. It sends the project inside { "payload": ... }, which is the request shape the API expects.
These are the essential calls from the supplied code. The helper functions are included in the ZIP; you do not need to write them:
const request = buildRequest(project, captions);
const quote = await zvid.authoring.validate(request);
checkQuote(quote, Number(process.env.MAX_RENDER_CREDITS || 8));
const accepted = await zvid.renders.create(request);
const job = await trackJob(zvid, accepted.jobId);
await downloadVideo(outputUrl(job), 'out/subtitled.mp4');
Validation uses POST /api/render/validate/api-key. Submission uses POST /api/render/api-key. Tracking uses GET /api/jobs/{jobId}. Wait for state: "completed". A job can still be active when its progress reaches 100%.
Optional detail: interpret validation results and job state and progress.
4. Open the downloaded video
Success ends with:
State: completed (100%)
Saved out/subtitled.mp4
Open out/subtitled.mp4 in your video player. You should hear all three sentences, see the matching captions and have an unclipped picture. Compare it with the after clip above, or download that reference output.
The script also saves the submission response, job ID and final job response in out/. It downloads only after completion and checks the download response before saving the MP4. Keep your local copy; hosted render outputs can expire.
If the terminal closes or a request times out, run:
npm run resume
This tracks the saved job and downloads its result without starting another render. If submission was interrupted before a job ID was saved, check Renders in the dashboard before trying again. Do not assume a missing response means no job was created.
Optional detail: output URLs and completion.
How the captions line up with the clip
Each caption supplies three things: what to display, when to appear and when to disappear. Times are seconds from the start of the finished video. 0.5 means half a second, not 500 milliseconds.
This is the entire captions.json file:
[
{ "start": 0.5, "end": 2.25, "text": "Take a slow breath." },
{ "start": 2.66, "end": 4.45, "text": "Notice the light on the water." },
{ "start": 5.14, "end": 6.6, "text": "Stay here for a moment." }
]
- 1. Take a slow breath. 0.50 to 2.25s
- 2. Notice the light on the water. 2.66 to 4.45s
- 3. Stay here for a moment. 5.14 to 6.60s
The script puts this array in subtitle.captions at the project root, alongside visuals. The video layer uses volume: 1 to retain its narration. The subtitle style comes from project.json:
{
"animation": "normal",
"font": { "family": "Inter", "size": 42, "color": "#FFF9EF", "bold": true },
"background": { "color": "#201A2E", "opacity": 0.94, "padding": 18, "radius": 8 },
"position": "bottom-center",
"margin": { "x": 48, "y": 176 }
}
normal shows the complete sentence for its interval. The dark background separates it from the bright water. Font size and margins are pixels on this 720 × 1280 canvas. Increasing margin.y moves bottom captions farther up; check the destination player’s controls before choosing your own margin.
This sample leaves maxWordsPerLine unset. That option splits captions into successive timed groups, which is different from keeping a complete sentence on screen. Animated word highlighting also needs careful word timing. Zvid can distribute word times from text length, but that calculation does not listen to speech.
Optional detail: subtitle fields and timing and available animations.
If something fails
The script stops on a failed job, a request timeout or a download error. It waits up to ten minutes for completion, with a separate timeout for each request. It does not automatically retry a paid submission.
| What you see | What to do |
|---|---|
| Missing key or HTTP 401 | Check that .env contains your key and that you are running from the extracted folder. Keep the key out of logs and shared files. |
| Validation error | Read out/validation.json. For inline captions, supply subtitle.captions and remove subtitle.src. The script also rejects empty text, overlapping captions and times outside the eight-second clip. |
| Estimate exceeds the limit | Review the request and quote. Change MAX_RENDER_CREDITS only if you intend to spend that amount and have enough available credits. |
state: "failed" |
Read failedReason in out/job.json. Correct the reported issue before deliberately creating another render. Resuming a failed job does not repair it. |
| Timeout or download error after a job ID was saved | Run npm run resume. It reuses the saved job. A render still running on the server is not cancelled by the local timeout. |
The sample records a submission attempt before sending it. To intentionally make a new video, first check the previous job in the dashboard and rename out to keep its record. Then run validation and render again. This prevents an accidental rerun from spending credits twice.
For deeper handling, see failures and output retention. For help with a specific job, use https://zvid.io/contact.
Try your own clip
Replace the hosted video URL in data/project.json with a direct HTTPS video URL that the renderer can access. Set the project duration and dimensions for that clip, then replace the text and times in data/captions.json. A file path on your laptop will not work as a remote media URL.
Prepare the timing from the final recording. You can do that by listening and marking the sentences, or by using a separate transcription service and reviewing its output. This Node.js example does not generate captions from audio.
Start with static captions. Watch the longest sentence, the brightest background and the beginning and end of each caption. Confirm the audio still matches and nothing is cropped. Once that version reads comfortably, experiment with styling or word animation.
Frequently asked questions
Can this JSON example generate subtitles automatically from audio?
No. This example uses caption text and start/end times that you supply in captions.json. Prepare the timing from the final recording, or use a separate transcription service and review its output before adding it to the project.
Are subtitle start and end times measured in seconds?
Yes. Each caption's start and end values are seconds from the beginning of the finished video. For example, 0.5 starts a caption half a second into the video. Keep each interval within the project duration and check the timing against the audio.
Does the subtitle example keep the original audio?
Yes. The supplied project sets the video layer's volume to 1, retaining the clip's narration. Listen to the downloaded result and confirm that all three captions match the spoken sentences.
How do I resume a subtitle render without submitting it again?
Run npm run resume after the example has saved a job ID. It tracks that existing job and downloads the output when the job is completed. If submission stopped before an ID was saved, check Renders in the dashboard before submitting again, because a missing response does not prove that no job was created.