This tutorial creates a small TypeScript app with a camera preview, licence status, and controls to apply or clear a local effect. You can verify the camera setup before obtaining an effect file.
For a larger example with beauty, makeup, Cloud Filters, and other controls, see the official vanilla TypeScript example.
Prerequisites
- Node.js
20.19or later on Node 20, or Node.js22.12or later, for Vite - A camera and a browser with WebGL2, WebAssembly SIMD, and Web Crypto
- A Web licence key registered for your development origin, and for your production origin before deployment
- HTTPS in production or
localhostfor development - Optional: a Web-compatible
.nosmaieffect file that your licence permits you to use
1. Create the app and install the SDK
Create a Vite app using its vanilla TypeScript template:
npm create vite@latest nosmai-web-demo -- --template vanilla-ts cd nosmai-web-demo npm install npm install @nosmai/[email protected]
If you already have a browser TypeScript app, install @nosmai/[email protected] in that app and adapt the page and entry-module paths below to your project.
2. Prepare the runtime assets
Create prepare-nosmai-assets.mjs in the project root using the copy script in Web installation. Then run it:
node prepare-nosmai-assets.mjs
Your app must serve the SDK's engine/, engine-baseline/, and models/ directories from public/nosmai. The example below uses assetBase: '/nosmai'. Keep these assets from the same 1.0.0 release as the installed package, and run the copy script before deployment builds too.
3. Add the page
Replace the Vite project's root index.html with:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nosmai camera preview</title>
</head>
<body>
<main>
<h1>Nosmai camera preview</h1>
<canvas id="preview" style="display: block; width: 100%; max-width: 640px;"></canvas>
<button id="start" type="button">Start camera</button>
<button id="stop" type="button" disabled>Stop camera</button>
<p>
<label>
Choose a .nosmai effect
<input id="effect-file" type="file" accept=".nosmai" disabled />
</label>
<button id="clear-effect" type="button" disabled>Clear effect</button>
</p>
<p id="status" role="status">Ready to start</p>
<p id="licence-status" role="status">Licence: not checked</p>
</main>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
4. Initialize the SDK and connect the controls
Replace src/main.ts with the following code. Insert your Web licence key in WEB_LICENSE_KEY:
import { Nosmai, NosmaiError } from '@nosmai/web-sdk'
const WEB_LICENSE_KEY = 'NOSMAI-YOUR-WEB-API-KEY'
const canvas = document.querySelector<HTMLCanvasElement>('#preview')!
const startButton = document.querySelector<HTMLButtonElement>('#start')!
const stopButton = document.querySelector<HTMLButtonElement>('#stop')!
const effectInput = document.querySelector<HTMLInputElement>('#effect-file')!
const clearButton = document.querySelector<HTMLButtonElement>('#clear-effect')!
const statusLabel = document.querySelector<HTMLParagraphElement>('#status')!
const licenceLabel = document.querySelector<HTMLParagraphElement>('#licence-status')!
const sdk = Nosmai.instance
let attached = false
let busy = false
function updateControls(): void {
const running = sdk.camera.isRunning
startButton.disabled = busy || running
stopButton.disabled = busy || !running
effectInput.disabled = busy || !running
clearButton.disabled = busy || !running
}
function showError(error: unknown): void {
statusLabel.textContent = error instanceof NosmaiError
? error.userMessage
: error instanceof Error ? error.message : String(error)
console.error(error)
}
async function run(action: () => Promise<void>): Promise<void> {
if (busy) return
busy = true
updateControls()
try {
await action()
} catch (error) {
showError(error)
} finally {
busy = false
updateControls()
}
}
sdk.on('error', showError)
sdk.on('licenseStatusChanged', (state) => {
licenceLabel.textContent = `Licence: ${state.status}`
})
startButton.addEventListener('click', () => {
void run(async () => {
statusLabel.textContent = 'Starting camera...'
if (!attached) {
const result = await Nosmai.initialize(WEB_LICENSE_KEY, {
assetBase: '/nosmai',
})
if (!result.ok) {
throw result.error ?? new Error('Nosmai initialization failed')
}
await sdk.attach(canvas)
attached = true
}
await sdk.camera.start({ position: 'front', width: 640, height: 480 })
statusLabel.textContent = 'Camera ready'
})
})
stopButton.addEventListener('click', () => {
sdk.camera.stop()
statusLabel.textContent = 'Camera stopped'
updateControls()
})
effectInput.addEventListener('change', () => {
const file = effectInput.files?.[0]
if (!file) return
effectInput.value = ''
void run(async () => {
statusLabel.textContent = 'Loading effect...'
await sdk.effects.apply(file)
statusLabel.textContent = `Effect applied: ${file.name}`
})
})
clearButton.addEventListener('click', () => {
void run(async () => {
await sdk.effects.clear()
statusLabel.textContent = 'Effect cleared'
})
})
window.addEventListener('pagehide', () => {
sdk.dispose()
attached = false
busy = false
statusLabel.textContent = 'Camera stopped'
licenceLabel.textContent = 'Licence: not checked'
updateControls()
})
initialize configures the SDK. Attaching the mounted canvas loads the runtime assets and starts licence verification. The licence result arrives through licenseStatusChanged; a successful initialize result alone does not confirm that the key has been verified.
The camera starts from the Start camera button. The requested 640 × 480 resolution is a preference; the actual resolution depends on the camera and browser. Stop camera releases the camera while keeping the preview runtime available for another start. dispose() releases the SDK when leaving the page. In a component-based app, also dispose the preview when its owning component unmounts.
5. Run the camera preview
Start the development server:
npm run dev
Open the printed localhost URL, click Start camera, and grant camera permission. Confirm that this exact origin is allowed by your Web licence key. If the development server selects another port, check the origin rules for that URL too.
You should see the live camera and the status Camera ready. The licence label may show unverified while verification is pending. With a valid key, an allowed origin, and a successful verification request, it should change to valid.
6. Apply an effect
While the camera is running, use Choose a .nosmai effect to select a Web-compatible effect file. The example passes that file to sdk.effects.apply(file). After loading succeeds, the status shows the file name. Use Clear effect to remove it.
Use a Web-compatible effect exported from Nosmai Studio or obtained through your licensed asset workflow. Effect files and access to their required features are separate from installing the npm package. You can complete the camera preview check without an effect file.
Verify it worked
- Start camera displays a live preview and Camera ready.
- The licence label reports the verification result independently of the camera status.
- If you selected a compatible effect, it appears in the preview and Clear effect removes it.
- Stop camera releases camera capture, and Start camera restarts it.
- The browser console and Network panel show no failed runtime asset requests.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Runtime or model request returns 404 | Runtime assets are missing or assetBase points to the wrong URL | Repeat the installation guide's asset-copy step and check the public asset URLs |
webglUnavailable | Graphics support is unavailable, or runtime startup failed | Check the underlying error, asset responses, WebGL2, WebAssembly SIMD, and hardware acceleration |
cameraPermissionDenied | User or browser policy denied camera access | Use HTTPS or localhost, grant permission, and allow camera access on any parent iframe |
cameraUnavailable | No camera is available or another app is using it | Connect a camera and close other apps or tabs using it |
Licence remains unverified | Verification is pending or the licence service could not be reached | Check your connection and Content Security Policy, then inspect the verification request |
Licence is invalid or expired | The key, registered origin, or licence validity does not match this app | Check the Web key and origin in Nosmai Console and follow the licence guide |
effectInvalidFormat or effectLoadFailed | The file is damaged, incompatible, or could not be loaded | Use an unmodified Web-compatible .nosmai effect and inspect the error details |