Nuxt 3
Integration guide for Nuxt 3. Uses the @swake/web SDK, which works with any JavaScript framework or vanilla JS.
Overview
@swake/web is a framework-agnostic feedback SDK — one core client plus an optional UI widget layer (@swake/web/ui) that renders a trigger button, feedback form, history panel, and survey modals inside a Shadow DOM. In Nuxt, it's wired up once via a client-only plugin and accessed anywhere through a useSwake() composable.
A few concepts come up throughout this guide:
| Concept | What it is |
|---|---|
apiKey | Your project's key, the only required option to Swake.init(). |
identify() | Links feedback, surveys, and notifications to a user. Almost everything downstream depends on it. |
| Offline queue | Submissions are queued in localStorage and retried automatically — this happens for every call, with no extra code. |
| Theme | A single theme object, referenced by nearly every widget, applied as CSS custom properties. |
Getting Started
Requirements
| Nuxt | 3.0 or later |
| Vue | 3.3 or later (included with Nuxt 3) |
| Browser | Chrome 80+, Firefox 78+, Safari 14+, Edge 80+ |
| Node.js | 18+ (for build tooling) |
Swake is a browser-only SDK. In Nuxt's SSR environment, it must run exclusively on the client. This guide uses a .client.ts plugin to ensure server-safety.
Installation
npm install @swake/web-swake-sdk
# or
yarn add @swake/web-swake-sdk
# or
pnpm add @swake/web-swake-sdk
The package exports two entry points:
| Import | Purpose |
|---|---|
@swake/web | Core SDK — init, identify, submit, notifications, surveys, breadcrumbs |
@swake/web/ui | Visual widgets — trigger FAB, feedback form, history panel, survey modals (rendered in Shadow DOM) |
Plugin Setup
Create a client-only Nuxt plugin. The .client.ts suffix ensures it only runs in the browser — never during SSR.
import Swake from '@swake/web';
import '@swake/web/ui';
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig();
Swake.init({
apiKey: config.public.swakeApiKey,
appVersion: config.public.appVersion || '1.0.0',
surveys: {
enabled: true,
autoShow: true,
delay: 3000,
cooldown: 86_400_000,
},
breadcrumbs: {
captureNavigation: true,
captureNetwork: true,
captureConsole: true,
captureClicks: true,
},
trigger: { position: 'bottom-right' },
});
return {
provide: { swake: Swake },
};
});
Runtime config
export default defineNuxtConfig({
runtimeConfig: {
public: {
swakeApiKey: process.env.NUXT_PUBLIC_SWAKE_API_KEY || '',
appVersion: process.env.NUXT_PUBLIC_APP_VERSION || '1.0.0',
},
},
});
NUXT_PUBLIC_SWAKE_API_KEY=ep_live_your_api_key
NUXT_PUBLIC_APP_VERSION=1.0.0
The plugin provides the Swake namespace as $swake via useNuxtApp(). You can access it from any component or composable.
Full init options
accepts a single configuration object. Every property except apiKey is optional.
Swake.init({
apiKey: 'ep_live_your_api_key', // required
baseUrl: 'https://api.swake.io', // optional — override for self-hosted or a proxy
debug: false, // verbose console logs
appVersion: '1.0.0', // shown per submission in portal
autoCapture: {
browserInfo: true, // attach browser/OS info to submissions
},
surveys: {
enabled: true, // fetch & show eligible surveys
autoShow: true, // auto-show after identify()
delay: 3000, // ms before auto-show
cooldown: 86_400_000, // ms between surveys (default: 24h)
},
breadcrumbs: {
enabled: true, // attach breadcrumb trail
maxEntries: 50, // ring buffer size (max 100)
captureNavigation: true, // pushState / popstate
captureNetwork: true, // fetch() and XMLHttpRequest
captureConsole: true, // console.warn / console.error
captureClicks: true, // element click events
},
trigger: {
position: 'bottom-right', // 'bottom-left' | 'top-right' | 'top-left'
icon: 'chat', // 'feedback' | 'bug' | 'idea'
label: 'Feedback',
hidden: false,
zIndex: 999999,
style: {
backgroundColor: '#059669',
size: 56,
borderRadius: 28,
shadow: true,
},
},
theme: { /* see Theme Customization section */ },
onLimitReachedMode: 'default_ui', // 'silent' | 'callback_only'
onLimitReached: (event) => {
console.warn(event.limitKey, event.message);
},
});
Composable Pattern
For production apps, create a useSwake() composable that wraps SDK access, handles identity, and polls for unread notifications.
import type Swake from '@swake/web';
export function useSwake() {
const { $swake } = useNuxtApp() as { $swake: typeof Swake };
const userId = useState<string | null>('swake-user', () => null);
const unreadCount = useState<number>('swake-unread', () => 0);
let pollTimer: ReturnType<typeof setInterval> | null = null;
async function identify(uid: string, email?: string, name?: string) {
await $swake.identify({ userId: uid, email, name });
userId.value = uid;
startPolling();
}
function logout() {
$swake.clearIdentity();
userId.value = null;
unreadCount.value = 0;
stopPolling();
}
async function refreshUnread() {
if (!userId.value) return;
try {
unreadCount.value = await $swake.getUnreadCount();
} catch { /* non-fatal */ }
}
function startPolling() {
stopPolling();
void refreshUnread();
pollTimer = setInterval(refreshUnread, 60_000);
}
function stopPolling() {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
}
return {
swake: $swake,
userId: readonly(userId),
unreadCount: readonly(unreadCount),
identify,
logout,
refreshUnread,
};
}
Use in a component
<script setup lang="ts">
const { userId, unreadCount, identify, logout } = useSwake();
</script>
<template>
<header>
<template v-if="userId">
<span>Notifications: {{ unreadCount }}</span>
<button @click="logout">Log out</button>
</template>
<button v-else @click="identify('user_123', 'user@example.com', 'Jane')">
Log in
</button>
</header>
</template>
Auto-identify with auth middleware
If you use Nuxt auth (e.g. sidebase/nuxt-auth or Supabase), wire identification in a client middleware or a watch:
export function useSwakeAuth() {
const { identify, logout } = useSwake();
const { data: session } = useAuth(); // your auth composable
watch(
() => session.value,
(session) => {
if (session?.user) {
identify(session.user.id, session.user.email, session.user.name);
} else {
logout();
}
},
{ immediate: true },
);
}
Identifying Users
Call after your user logs in. This links all feedback, survey responses, and notifications to that user.
const { $swake } = useNuxtApp();
await $swake.identify({
userId: 'user_123', // required — your app's user ID
email: 'jane@example.com', // optional
name: 'Jane Smith', // optional
metadata: { // optional — arbitrary key-value pairs
plan: 'pro',
company: 'Acme Corp',
},
});
| Parameter | Type | Description |
|---|---|---|
userId | string | Your app's unique user ID (required) |
email | string | User's email. Preserved if omitted on subsequent calls. |
name | string | User's display name. Preserved if omitted on subsequent calls. |
metadata | Record<string, string> | Custom key-value pairs. Fully replaced on each call — send the complete set. |
Clearing identity on logout
$swake.clearIdentity();
Wipes the stored user ID and clears the offline queue.
Feedback
Feedback Form
Open the built-in feedback form widget. Requires the @swake/web/ui import in your plugin.
const { $swake } = useNuxtApp();
// Default form
$swake.showFeedbackForm();
// With options
$swake.showFeedbackForm({
defaultType: 'feature', // pre-select type: 'bug' | 'feature' | 'question'
showTypeSelector: true, // show/hide type toggle (default: true)
title: "What's on your mind?", // header text
placeholder: 'Tell us more...', // textarea placeholder
theme: { primaryColor: '#8B5CF6' }, // per-call theme override
});
| Option | Type | Default |
|---|---|---|
defaultType | 'bug' | 'feature' | 'question' | 'bug' |
showTypeSelector | boolean | true |
title | string | "What's on your mind?" |
placeholder | string | 'Tell us more...' |
theme | SwakeWebTheme | global theme |
Custom trigger button
Hide the built-in FAB and wire the form to your own button:
<script setup lang="ts">
const { $swake } = useNuxtApp();
</script>
<template>
<button @click="$swake.showFeedbackForm({ defaultType: 'bug' })">
Report a Bug
</button>
</template>
<!-- In your plugin, hide the trigger:
trigger: { hidden: true }
-->
Submitting Feedback
Submit feedback programmatically. Browser info and breadcrumbs are automatically attached.
const { $swake } = useNuxtApp();
const submission = await $swake.submitFeedback({
type: 'bug', // 'bug' | 'feature' | 'question'
title: 'Search returns no results', // required
description: 'Reproducible on Safari + macOS 14.', // optional
attachments: [ // optional — File objects
{ file: screenshotFile },
],
});
console.log('Created:', submission.id);
| Parameter | Type | Description |
|---|---|---|
type | 'bug' | 'feature' | 'question' | Submission category (required) |
title | string | Brief summary (required) |
description | string | Detailed description |
attachments | { file: File }[] | File objects from <input type="file"> or drag-and-drop |
customFields | Record<string, string> | Project custom field values as a { fieldId: value } map — fetch definitions with getCustomFields(); required fields enforced |
Feedback History
Show a panel listing the current user's past submissions with status badges and a detail view with replies. Requires the user to be identified.
const { $swake } = useNuxtApp();
// Open the built-in history panel
$swake.showFeedbackHistory();
Programmatic access
// Lightweight list (id, title, status, type, createdAt)
const { submissions, hasMore, cursor } = await $swake.getHistory({ limit: 20 });
// Full submission detail with comments + attachments
const submission = await $swake.getSubmission('submission_id');
// Paginated submission list with more fields
const result = await $swake.listSubmissions({ limit: 10 });
Trigger Button (FAB)
When you import @swake/web/ui in your plugin, a floating action button appears automatically. Configure it via the trigger option in Swake.init().
Swake.init({
apiKey: 'ep_live_...',
trigger: {
position: 'bottom-right', // 'bottom-left' | 'top-right' | 'top-left'
icon: 'chat', // 'feedback' | 'bug' | 'idea'
label: 'Feedback',
hidden: false,
zIndex: 999999,
style: {
backgroundColor: '#059669',
size: 56,
borderRadius: 28,
shadow: true,
},
},
});
Show / hide at runtime
const { $swake } = useNuxtApp();
// Hide the FAB (e.g. during onboarding)
$swake.setTriggerVisible(false);
// Show it again
$swake.setTriggerVisible(true);
// Programmatic open / close
$swake.open(); // opens the feedback form
$swake.close(); // closes any open widget
All widgets are rendered inside a closed Shadow DOM container. Your Nuxt app's CSS never leaks in, and widget styles never leak out.
Engagement
Surveys & NPS
Surveys, NPS polls, and multiple-choice polls are created in the Swake portal. The SDK handles targeting, display, and response submission.
const { $swake } = useNuxtApp();
// Re-check eligibility and show the first match
await $swake.checkSurveys();
// Show a specific survey by ID (ignores cooldown)
await $swake.showSurvey('survey_abc123');
Event listeners
Register these in your plugin after Swake.init():
Swake.onSurveyShown((event) => {
console.log('Survey shown:', event.id, event.type);
});
Swake.onSurveyCompleted((event) => {
console.log('Completed:', event.survey.id, 'answers:', event.response.answers);
});
Swake.onSurveyDismissed((event) => {
console.log('Dismissed:', event.id);
});
Survey targeting (user traits, segments, days active) is evaluated server-side. The SDK caches eligible surveys per project for 5 minutes.
Voting Board
Let users browse and vote on public board items. Fetching items does not require identification, but voting does.
const { $swake } = useNuxtApp();
// Fetch board items
const { items, hasMore } = await $swake.getBoardItems('public-roadmap', {
sort: 'votes', // 'votes' | 'recent'
status: 'open', // 'open' | 'in_progress' | 'resolved' | 'closed'
page: 1,
});
// Cast a vote (requires identify)
const { status, voteCount } = await $swake.vote('public-roadmap', 'item_id');
// Remove a vote
const result = await $swake.removeVote('public-roadmap', 'item_id');
Notifications
Notifications
The SDK provides in-app notifications for status changes and team replies. The trigger FAB shows an unread badge automatically (polled every 60 seconds).
const { $swake } = useNuxtApp();
// Get unread count
const count = await $swake.getUnreadCount();
// List notifications
const { notifications, pagination } = await $swake.listNotifications({
unreadOnly: true,
limit: 20,
});
// Mark as read
await $swake.markNotificationRead('notification_id');
// Mark all as read
await $swake.markAllNotificationsRead();
Customization
Theme Customization
Pass a theme object in Swake.init() to brand the trigger button, feedback form, survey modal, and history panel.
Swake.init({
apiKey: config.public.swakeApiKey,
theme: {
primaryColor: '#8B5CF6', // buttons, active states, FAB
successColor: '#10B981', // success states
dangerColor: '#EF4444', // error states
backgroundColor: '#FFFFFF', // panel backgrounds
surfaceColor: '#F8FAFC', // cards, input backgrounds
overlayColor: 'rgba(15,23,42,0.4)', // backdrop
textColor: '#0F172A', // primary text
textSecondary: '#64748B', // muted text
borderColor: '#E2E8F0', // borders, dividers
borderRadius: 12, // px
fontFamily: 'Inter, sans-serif',
},
});
Available tokens
| Token | Default | Description |
|---|---|---|
primaryColor | #6366F1 | Buttons, active states, FAB background |
successColor | #10B981 | Success checkmark, resolved badges |
dangerColor | #EF4444 | Error borders, destructive actions |
backgroundColor | #FFFFFF | Modal / panel background |
surfaceColor | #F9FAFB | Input fields, secondary surfaces |
overlayColor | rgba(0,0,0,0.45) | Backdrop behind modals |
textColor | #111827 | Primary text |
textSecondary | #6B7280 | Labels, placeholders, metadata |
borderColor | #E5E7EB | Input borders, dividers |
borderRadius | 8 | Corner radius for inputs and buttons |
fontFamily | System default | Font family applied to all text |
Per-call overrides
showFeedbackForm() accepts an optional theme that merges on top of the global theme.
$swake.showFeedbackForm({
theme: { primaryColor: '#0EA5E9' },
});
Shadow DOM isolation: theme tokens are scoped to the Swake widget root via CSS custom properties (--swake-primary, --swake-bg, etc.) and never leak into your Nuxt app styles.
Breadcrumbs
Breadcrumbs capture a trail of user actions and are automatically attached to every submission. Stored in a ring buffer (default 50, max 100).
Auto-captured events
| Category | Config key | What it captures |
|---|---|---|
navigation | captureNavigation | pushState, popstate (Nuxt route changes) |
network | captureNetwork | fetch() and XMLHttpRequest calls |
console | captureConsole | console.warn and console.error |
click | captureClicks | Element click events with CSS selector |
Manual breadcrumbs
const { $swake } = useNuxtApp();
$swake.addBreadcrumb({
category: 'custom',
message: 'User upgraded to Pro plan',
data: { plan: 'pro', via: 'settings' },
});
// Read the current trail
const trail = $swake.getBreadcrumbs();
// Clear the buffer
$swake.clearBreadcrumbs();
All auto-capture categories are enabled by default. Disable individual categories by setting them to false in breadcrumbs config.
Offline
Offline Queue
When the user is offline, submissions are queued in localStorage and automatically retried when connectivity returns.
import { offlineQueue } from '@swake/web';
// Check queue size
const pending = offlineQueue.size();
// Force a flush attempt
await offlineQueue.flush();
clearIdentity() clears the offline queue. Always call it on logout to prevent queued items from being sent after a different user logs in.
AI Setup
Using Claude Code
Prefer to let an AI coding agent do the wiring? Run Claude Code from the root of your Nuxt project and paste the prompt below. It reads this page as the source of truth, detects your stack, asks you for your API key and anything else it needs, then wires up @swake/web, init(), identify(), the widgets, and theming — in one shot.
Prerequisites
Before you run the prompt, set up your project in the Swake portal and grab the values the agent will ask for — it only writes placeholders to your env files, so you supply the real values yourself.
- Sign in to the Swake portal and create a project (or open an existing one).
- In Project settings → API keys, get existing or create a key and copy it — it's shown once and starts with
ep_live_. - If you want the voting board, create a board and copy its slug from the board's URL / settings.
Have these ready when the agent prompts you — the same values you'd otherwise wire up by hand:
| Value | Where to find it | Example |
|---|---|---|
apiKey | Project settings → API keys | ep_live_… |
baseUrl | API endpoint — optional, only needed when self-hosting or routing through your own backend | https://api.swake.io |
boardSlug | Voting board settings — optional; passed to getBoardItems() / vote(), not init() | public-roadmap |
The prompt is additive and safe: a Swake or network error must never break your app's boot or existing behavior. The agent pauses and asks before installing packages or writing secrets, and it never guesses APIs that aren't in these docs. It also asks whether to keep your ep_live_ key server-side behind your own backend — the recommended setup for any app that has one, since the key never reaches the browser and the submitting user can't be spoofed.
The prompt
Run Claude Code from your project root and paste this. It targets Nuxt 3 specifically, and re-reads this guide before it writes anything, so it stays correct as the SDK evolves.
Fully integrate the Swake feedback SDK (feedback forms, bug reports, surveys/NPS, in-app notifications, voting boards) into this Nuxt 3 app. Treat it as additive: a Swake or network failure must NEVER break boot or any existing behavior. Never invent or fake an API that is not in the docs.
1. READ THE DOCS FIRST — they are the source of truth for the package, init/identify, the widget layer and every option. Fetch with a browser User-Agent (a plain fetch returns 403): curl -sL -A "Mozilla/5.0" "https://swake.io/docs/sdk?framework=nuxt". Confirm the Nuxt major version and whether SSR is enabled before you edit anything.
2. ASK BEFORE DECIDING ANYTHING (AskUserQuestion): (a) integration mode — DIRECT, meaning the ep_live_ key ships in the browser via runtimeConfig.public.swakeApiKey (fine for a static or SPA-only app), or PROXY, meaning the key stays server-side in a Nitro server route (recommended whenever a backend exists — see step 4); (b) the API key or proxy path, an optional baseUrl, and a voting-board slug if they want the board. Write PLACEHOLDERS ONLY into env files (and the .example alongside) — never commit a real key. ASK again before installing any package.
3. INSTALL AS A CLIENT PLUGIN — add @swake/web and create plugins/swake.client.ts. The .client suffix IS the SSR guard: Nuxt only ever runs that file in the browser, so no import.meta.client checks or onMounted wrappers are needed. Load the widgets there with await import('@swake/web/ui'). Read config from useRuntimeConfig().public and declare it in nuxt.config.ts.
4. INIT EXACTLY ONCE, IDEMPOTENTLY — keep a module-level "let initPromise: Promise<void> | null" and have every caller await the SAME promise. This is required, not stylistic: the SDK exposes no isInitialized(), every method throws "[Swake] SDK not initialized" before init(), and a second init() starts a second offline-queue flush interval without clearing the first. Swake.init() itself is synchronous. PROXY mode: pass any non-empty placeholder as apiKey, point baseUrl at a Nitro route you add at server/api/swake/[...].ts, which forwards method, path, query and body to the Swake API, and set credentials: 'include'. That backend attaches the real X-API-Key server-side, overrides any client-supplied externalUserId with the session user so identity cannot be spoofed, and must allow X-API-Key and Idempotency-Key through CORS. Set trigger: { hidden: true } if the app will open feedback from its own button instead of the floating one.
5. IDENTITY — after init resolves, call Swake.identify({ userId, email, name, metadata }) on EVERY load that has a session, not just on the login event: identity is held in memory only, so a page refresh loses it. userId must be your stable internal id, and every metadata value must be a string. On logout call Swake.clearIdentity() inside a try/catch — it throws if init never ran. Watch your user composable (useUserSession, useSupabaseUser, or whatever is present) with { immediate: true } so a session restored on load identifies too.
6. POLISH — drive Swake.setTheme() from the app's light/dark toggle (widgets otherwise keep the theme captured at init); gate init/identify by route so an auto-shown survey can never land on login, signup, or onboarding; add Swake.addBreadcrumb() at meaningful domain events so bug reports arrive with context.
7. VERIFY & REPORT — funnel every SDK call through one wrapper with try/catch, then prove it end to end: the trigger opens the form, a real submission appears in the Swake dashboard, and no survey shows on an auth or onboarding route. Report the files you changed, any manual steps left for me, and every assumption you made. Confirm it against a real SSR build (nuxi build && nuxi preview), not just dev.
Reference
Full API Reference
All methods are available on the $swake instance provided by the plugin. Click any method for its full signature, parameters, and an example.
| Method | Description |
|---|---|
| Initialise the SDK. Must be called once before any other method. | |
| Link the current user. Returns a Promise. | |
| Clear user identity and offline queue. | |
| Replace the global UI theme at runtime. | |
| Submit feedback programmatically (with optional customFields). Returns the created Submission. | |
| Fetch the project's custom field definitions for a custom feedback UI. | |
| Open the built-in feedback form widget. | |
| Open the feedback history panel. | |
| Open the feedback form (alias). | |
| Close any open widget (form, history, survey). | |
| Show or hide the trigger FAB. | |
| List the current user's submissions. | |
| Get full submission detail with comments + attachments. | |
| Edit a submission you own. | |
| Unpublish a submission you own (one-way). | |
| Lightweight submission history. | |
| Get unread notification count. | |
| List notifications with pagination. | |
| Mark a single notification as read. | |
| Mark all notifications as read. | |
| Re-check survey eligibility and show the first match. | |
| Show a specific survey (ignores cooldown). | |
| Register survey-shown event listener. | |
| Register survey-completed event listener. | |
| Register survey-dismissed event listener. | |
| Fetch voting board items. | |
| Cast a vote on a board item. | |
| Remove a vote from a board item. | |
| Add a custom breadcrumb to the trail. | |
| Return a snapshot of the breadcrumb trail. | |
| Clear the breadcrumb ring buffer. | |
| Register plan-limit event listener. | |
| Tear down all listeners, timers, and UI. |