npm package
3DN SDK
Embed the 3DN product builder in any storefront. The SDK loads the builder, runs the login round-trip, refreshes the license, saves and reports every save. Your site supplies a session endpoint, a login-token endpoint and its own login UI.
createBuilder()
Safe during SSR. Touches the page only on load() or mount().
<threed-builder>
Loaded once per page from 3DN, mounted into your container.
Install
npm install @3dn-builder/builder ESM, zero runtime dependencies. Entry points: ., ./events (types and constants only) and ./testing (a fake <threed-builder> for unit tests). Installation keys stay on your server: createBuilder() rejects anything that looks like one, and any option that names where the builder loads from.
Create, mount, destroy
import { createBuilder } from '@3dn-builder/builder';
const builder = createBuilder({
session: {
get: ({ hostProductId }) => backend.getBuilderSession(hostProductId),
refreshLicense: () => backend.refreshBuilderLicense(),
},
login: {
getTokens: () => backend.mintBuilderTokens(), // null on 401
onRequired: (action) => showLogin(action), // 'logged-in' | 'redirected' | 'cancelled'
},
onSaved: (saved) => showSavedDesign(saved.productId),
onLicenseError: (error) => reportSetupError(error.code),
onCloseRequested: () => closeModal(), // the builder already asked about unsaved changes
});
// Mount into a container with a real height.
const instance = await builder.mount({ target: container, hostProductId: 'alpine-mug' });
// Add to cart: save first, then put the saved product on the cart line.
const design = await instance.save();
await cart.add({ variantId, properties: { threednProductId: design.productId } });
// Leaving the page or closing the modal for good.
instance.destroy();mount() resolves to an instance with the same open(), save(), refreshSession(), logout() and destroy(). The controller's versions act on the most recently mounted builder; with more than one builder on a page, call the instance.
The loading and license screens cover only your container by default, so the rest of the page stays usable while the builder loads. Pass loader: 'page' to mount() to block the whole window instead, for example when the builder opens as a full-screen modal.
The builder loads at the latest release unless you pass version. Every released version stays online, so a pinned version keeps loading, but it only keeps working while the 3DN API still accepts what it sends. Stay on 'latest' unless you need to hold a release back.
Which product, with which license
hostProductId is your own reference. Your session endpoint decides which 3DN product it opens: the shopper's saved copy when they have one, else the global product. The license token is minted by your backend with the installation key and cached per installation.
session: {
// Every mount, and refreshSession(). Guests included.
get(request: { hostProductId: string }): Promise<BuilderSession>;
// tdn-license-token-required. One call shared by every builder on the page.
refreshLicense(): Promise<{ licenseToken: string }>;
}
// Guest, or a shopper with no saved copy: the global product.
{ "licenseToken": "…", "productId": "<global 3DN product id>" }
// Logged-in shopper with a saved copy (tokens are an optional fast path).
{ "licenseToken": "…", "productId": "<shopper's copy id>",
"token": "…", "refreshToken": "…" }
// A private product also needs "viewToken".Shopper tokens, only when asked
Guests browse and design with the license token alone. When the builder gates an action, the SDK calls getTokens(); your endpoint mints tokens for the shopper in your own server session, or answers 401. Every request gets exactly one answer, and a result that arrives after logout() or destroy() is dropped.
login: {
// tdn-login-required. Your login-token endpoint: tokens, or null on 401.
getTokens(): Promise<{ token: string; refreshToken: string } | null>;
// null came back: show your login for the gated action.
onRequired(action: LoginRequiredAction): Promise<'logged-in' | 'redirected' | 'cancelled'>;
// getTokens() threw (5xx, network). Default 'cancel'.
onMintFailed?(): Promise<'retry' | 'cancel'>;
}
// Login by redirect: send the shopper back to this page with the resume marker.
import { loginReturnPath, isSafeReturnPath, consumeResumeMarker, hasDraft } from '@3dn-builder/builder';
onRequired: async () => {
location.assign('/login?return=' + encodeURIComponent(loginReturnPath()));
return 'redirected';
};
// On the login page: only redirect to isSafeReturnPath(returnPath).
// Back on the product page: reopen the builder; it finishes the pending save.
if (consumeResumeMarker()) await openDesigner();
if (hasDraft(globalProductId)) showResumeButton();save() and onSaved
onSaved fires once for every successful save, whether your code called save() or the shopper pressed the builder's Save button. A guest's first save makes their own copy: productId is then the copy, and later saves update it. onSaved never fires for a failed save, or when customization.record() rejected; the next save records again. The copy is named after the source and when it was saved, for example "Mug Grey – 19 Oct, 14:32", so a shopper's designs from one product can be told apart.
The builder saves only when asked: its Save button, Ctrl/Cmd+S, its close prompt, or your save(). Until then the shopper's unsaved work is kept as a draft on their device, never sent to the server. When they close the builder with unsaved changes, it asks Save, Don't save or Cancel first, so onCloseRequested only has to close: after Don't save it carries discarded: true, and your page should not ask again.
// Every successful save, however it started: instance.save() or the
// builder's own Save button. A save that created the shopper's copy is
// reported after the copy exists and customization.record() resolved.
onSaved(saved: { hostProductId: string; productId: string; version: number }): void;
// Host-started save. Resolves after onSaved with the same product.
const { productId, version } = await instance.save();
// Optional: link the shopper's copy to your product, called once per copy.
// asCopy: the shopper asked for a copy and keeps the original too. false when
// Save had to fork a product they don't own: the copy replaces the original.
customization: {
record(link: {
hostProductId: string;
sourceProductId: string;
savedProductId: string;
asCopy: boolean;
}): Promise<void>;
}Lock ordered designs
When an order is placed, your backend locks the ordered design with its installation key, at the version from onSaved. A locked design can never change again; there is no unlock. It opens read-only, with Download and Save as copy, and a save on it fails with reason: 'locked'. To change an ordered design, cancel the order and let the shopper order a copy. A 409 with code: 'geometry-not-accepted' locks nothing: the box's shape was updated since the shopper saved, so ask them to reopen the design and click Accept, then lock that save's version. A 409 with code: 'option-not-approved' locks nothing either: the design has a box option on (such as a window) that is not ready for print yet, so ask the shopper to turn it off in Box options, save, and lock that version; the view-only link gives no print files for such a design. The view-only link opens a design in a bare viewer (the model in 3D, with the 2D / Split / 3D switch, the animation slider, the camera angles and Download print files, and no editing tools) and downloads its print files without a login, for example for a print house; nothing can be saved or copied through it. Every model names the board it is made on, and none has a default: on a model whose board has not been chosen yet, Download print files is off in the builder and the viewer, with the note "Pick the model's board before downloading print files", and its print files, the view-only link's included, answer 409 with code: 'board-not-chosen'. Nothing on your side fixes it: ask 3DN to pick the model's board.
Price a box from the design the shopper saved, never from a typed size: GET /plugin/products/{id}/specs?version= returns its size, board, flat blank (nest it on your own sheets), one patch per foil or spot UV plate and a specsHash to store with the line. Before the design is saved, POST /plugin/products/{id}/quote gives the same specs for the template product at a size on a board, without finishes; price the line again at checkout.
// Your backend, when an order is placed: lock the ordered design.
// productId + version come from onSaved, stored on the cart line.
await fetch(`${API_BASE}/plugin/products/${productId}/lock`, {
method: 'POST',
headers: {
'x-installation-key': INSTALLATION_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ orderRef: order.id, version }),
});
// 409: the shopper saved again after that version, or another order
// already locked it. A repeat with the same orderRef is a no-op.
// 409 with code 'geometry-not-accepted': the box's shape was updated since
// the save; ask the shopper to reopen the design and click Accept.
// 409 with code 'option-not-approved': a box option (such as a window) is on
// that is not ready for print yet; the shopper turns it off and saves again.
// A view-only link for a print house: a bare 3D viewer + print files, no login.
const r = await fetch(
`${API_BASE}/plugin/products/${productId}/view-only-link`,
{ method: 'POST', headers: { 'x-installation-key': INSTALLATION_KEY } }
);
const { data: { url } } = await r.json();
// Its print files answer 409 with code 'board-not-chosen' while the model's
// board has not been chosen (no model has a default board): ask 3DN to pick it.
// Price a box from its saved design; nest specs.data.blank on your own sheets.
const specs = await fetch(
`${API_BASE}/plugin/products/${productId}/specs?version=${version}`,
{ headers: { 'x-installation-key': INSTALLATION_KEY } }
).then((r) => r.json());
// specs.data: size, materialId, blank, finishes[], specsHash.
// 409: that version is not stored (data.currentVersion).
// Before the design is saved: POST /plugin/products/{templateProductId}/quote
// { dims: { L, W, H }, materialId } (no finishes).Hide Download, Share, Save and Report a problem
features.download: false removes Download, and features.share: false removes Share, from the desktop and the phone layout, for example when shoppers should not take the artwork away. features.save: false makes a try-it-out editor: every tool and the 2D/3D switch stay, but Save, Save as copy, version history and the save state go; save() still works for your page. features.feedback: false hides Report a problem, where the shopper describes what went wrong and 3DN receives it with a recording of the session. All are shown unless you turn them off. Any other key, or a value that is not a boolean, is a CONFIG_INVALID error.
// Hide shopper actions. All are shown unless set to false.
createBuilder({
// ...session, login, callbacks
features: {
download: false, // no Download (print files, a design area's SVG)
share: false, // no Share
save: false, // no Save, Save as copy, version history or save state
feedback: false, // no Report a problem
},
});One error shape, three callbacks
class BuilderError extends Error {
readonly code: BuilderErrorCode;
readonly message: string; // safe to show; never contains a token
readonly retryable: boolean;
readonly fatal: boolean; // the mount cannot continue until refreshed or recreated
readonly reason?: DesignSaveFailureReason | LicenseErrorCode | 'customization';
readonly cause?: unknown;
}
onLicenseError(error: BuilderError): void; // code 'LICENSE_ERROR', fatal
onCloseRequested(detail: { productId?: string; hasUnsavedChanges: boolean; discarded: boolean }): void;
onStatusChange(detail: BuilderStatusDetail): void; // load progress, never a save
try {
await instance.save();
} catch (e) {
if (!(e instanceof BuilderError)) throw e;
if (e.code === 'LOGIN_CANCELLED') return;
showMessage(e.message, { retry: e.retryable });
}Error codes
| Code | When | Retryable | Fatal |
|---|---|---|---|
| CONFIG_INVALID | A bad option, a secret, or a script URL passed to createBuilder() or mount(). | no | yes |
| NOT_IN_BROWSER | load() or mount() called during server-side rendering. | no | no |
| LOAD_FAILED | The builder code did not load. The next call tries again. | yes | no |
| VERSION_CONFLICT | Another builder version already owns this page. | no | yes |
| SESSION_FAILED | session.get() rejected. | yes | no |
| LICENSE_ERROR | tdn-license-error. Fatal for this mount until the host refreshes or recreates the session. | no | yes |
| LOGIN_CANCELLED | A protected action ended because the shopper did not log in. The builder keeps working. | yes | no |
| SAVE_FAILED | tdn-design-save-failed, or the save succeeded but customization.record() failed. | per reason | no |
| SAVE_TIMEOUT | No save outcome within saveTimeoutMs (45 seconds by default), outside a login round-trip. | yes | no |
| EXPORT_FAILED | externalExport.run() rejected. The SDK replied with an error. | yes | no |
| EXPORT_TIMEOUT | externalExport.run() took longer than its timeout (120 seconds by default). The SDK replied with an error. | yes | no |
| DESTROYED | destroy() ran while the call was pending. | no | no |
Save failure reasons
| reason | code | Meaning |
|---|---|---|
| conflict | SAVE_FAILED | The design was saved elsewhere since it was opened (someone else, or the same shopper in another tab). The builder offers Reload latest or Save as a copy. |
| forbidden | SAVE_FAILED | This user may not write to the product. The builder offers request access or save as copy. |
| unauthorized | SAVE_FAILED | Login recovery ran and the save was still refused. |
| login-cancelled | LOGIN_CANCELLED | The shopper closed the login, or the host could not mint shopper tokens. |
| installation-inactive | SAVE_FAILED | The host installation is not active. A setup problem, not a user error. |
| license | SAVE_FAILED | This page is not licensed. A LICENSE_ERROR follows. |
| locked | SAVE_FAILED | An order locked this design: it can never change again. The builder shows it read-only and offers Save as copy. Not retryable. |
| outdated | SAVE_FAILED | The builder on the page is older than the server and can no longer save. The builder offers a page reload, which carries the unsaved design across where it can. Not retryable. |
| geometry-not-accepted | SAVE_FAILED | The box's shape was updated since the design was saved. The builder shows the new shape with an Accept button; until the shopper accepts, saves and downloads are refused. Accept saves the new shape and fires onSaved. Retryable once accepted. |
| error | SAVE_FAILED | Network or server failure. |
| customization | SAVE_FAILED | SDK only: the design was saved but customization.record() failed. A retried save() records again without saving again. |
Exact shapes
interface BuilderHostConfig {
environment?: 'production' | 'staging'; // default 'production'; 'staging' is refused in this release
version?: 'latest' | `${number}.${number}.${number}`; // default 'latest'
saveTimeoutMs?: number; // default 45_000, paused during login
session: { get(r: { hostProductId: string }): Promise<BuilderSession>;
refreshLicense(): Promise<{ licenseToken: string }> };
login?: { getTokens(): Promise<ShopperTokens | null>;
onRequired(action: LoginRequiredAction): Promise<LoginOutcome>;
onMintFailed?(): Promise<'retry' | 'cancel'> };
customization?: { record(link: CustomizationLink): Promise<void> };
features?: { download?: boolean; share?: boolean; save?: boolean; feedback?: boolean }; // each default true; false hides it from shoppers
onSaved?(saved: SavedDesignEvent): void;
onLicenseError?(error: BuilderError): void;
onCloseRequested?(detail: CloseRequestedDetail): void;
onStatusChange?(detail: BuilderStatusDetail): void;
debug?: boolean; // console log, tokens redacted
}
interface MountOptions {
target: HTMLElement;
hostProductId: string; // your reference, passed to session.get()
mode?: 'designer' | 'viewer'; // default 'designer'
designId?: string;
loader?: 'container' | 'page'; // default 'container': loading screen covers target only
observabilityContext?: string; // JSON object: where the builder's error reports came from
externalExport?: { run(request: ExportRequestedDetail, signal: AbortSignal): Promise<ExportFile[]>;
timeoutMs?: number }; // GLB only, default 120_000
}
interface BuilderSession { licenseToken: string; productId: string;
viewToken?: string; token?: string; refreshToken?: string }
interface ShopperTokens { token: string; refreshToken: string }
type LoginOutcome = 'logged-in' | 'redirected' | 'cancelled';
type LoginRequiredAction = 'save' | 'screenshot' | 'export' | 'upload' | 'share' | 'session';
interface CustomizationLink { hostProductId: string; sourceProductId: string; savedProductId: string;
asCopy: boolean }
interface SavedDesignEvent { hostProductId: string; productId: string; version: number }
interface SavedDesign { productId: string; version: number }
interface CloseRequestedDetail { productId?: string; hasUnsavedChanges: boolean; discarded: boolean }
interface BuilderStatusDetail { status: 'idle' | 'opening' | 'loading' | 'ready' | 'error';
step?: string; message?: string; error?: string }Angular example
Import the SDK in the browser only, mount after render, and destroy the instance with the component.
@Component({
selector: 'app-designer',
template: '<div #target style="height: 100%"></div>',
})
export class DesignerComponent implements OnDestroy {
@Input({ required: true }) productRef!: string;
@ViewChild('target', { static: true }) target!: ElementRef<HTMLElement>;
private instance?: BuilderInstance;
constructor() {
// Browser only: SSR never imports the SDK.
afterNextRender(async () => {
const { createBuilder } = await import('@3dn-builder/builder');
const builder = createBuilder({ session, login, onSaved: (s) => this.saved(s) });
this.instance = await builder.mount({
target: this.target.nativeElement,
hostProductId: this.productRef,
});
});
}
save() {
return this.instance?.save();
}
ngOnDestroy() {
this.instance?.destroy();
}
}