On every plan, including Free
Website SDK
A survey SDK in one script tag.
The script that shows UserLoop surveys on your site or in your web app, and a global called window.userloop for your code: identify a visitor, set attributes to target on, open a survey and listen for each answer.
Read the docsWhat is the UserLoop survey SDK?
The UserLoop Web SDK is a browser script, loaded from one tag, that shows your published website surveys and gives your code a global called window.userloop. You use it to say who the visitor is, set attributes that targeting rules read, open a survey at a moment you choose and listen for answers. It is 13 KB gzipped, sets no cookies and works on every plan, including Free.
- Loads from
- https://cdn.userloop.io/sdk-3/userloop.js
- Methods
- init, identify, setAttributes, track, page, show, close, reset, setLanguage, on, off, getVisitorId
- Events
- shown, answered, completed, dismissed, error
- It is not
- An npm package, a React or Vue component, or a mobile SDK
How it works
Three steps, and only the first is required
01
Add the snippet
Copy it from Settings, then Website, and put it once in the layout every page shares. From then on, every website survey you publish reaches the site with no code change.
02
Say who the visitor is
Call identify with your own user ID and setAttributes with facts your app knows, such as a plan. They travel with each answer, and targeting rules can read them.
03
Open and listen from code
Call show to open a survey at a moment you choose, or track to report an event and let targeting decide. Listen with on for each answer and completion.
Install
One snippet, in the document every page shares
The loader defines window.userloop at once as a stand-in that queues calls, then loads the SDK asynchronously. In a framework it still goes in once, never in a component that renders per route.
<!-- Once on every page, in the layout or template they all share -->
<script>
!function(w,d,o){if(w.userloop)return;var q=[],u=w.userloop={q:q};"init identify setAttributes track page show close reset setLanguage on off".split(" ").forEach(function(m){u[m]=function(){q.push([m,[].slice.call(arguments)])}});var s=d.createElement("script"),c=d.currentScript;s.async=1;s.src="https://cdn.userloop.io/sdk-3/userloop.js";if(c&&c.nonce)s.nonce=c.nonce;d.head.appendChild(s);u.init(o)}(window,document,{"siteKey":"SITE_KEY"});
</script><!-- Where you can only add a script src, such as a site builder -->
<script>
// window.userloop exists only once the script has loaded
window.addEventListener("UserLoopReady", function () {
userloop.setAttributes({ plan: "pro" });
});
</script>
<script async src="https://cdn.userloop.io/sdk-3/userloop.js" data-site-key="SITE_KEY"></script>// app/layout.tsx
import Script from "next/script";
const userloopLoader = `!function(w,d,o){if(w.userloop)return;var q=[],u=w.userloop={q:q};"init identify setAttributes track page show close reset setLanguage on off".split(" ").forEach(function(m){u[m]=function(){q.push([m,[].slice.call(arguments)])}});var s=d.createElement("script"),c=d.currentScript;s.async=1;s.src="https://cdn.userloop.io/sdk-3/userloop.js";if(c&&c.nonce)s.nonce=c.nonce;d.head.appendChild(s);u.init(o)}(window,document,{"siteKey":"SITE_KEY"});`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Script id="userloop" strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: userloopLoader }} />
</body>
</html>
);
}<!doctype html>
<html lang="en">
<head>
<!-- index.html at the project root. Never render the snippet from a component. -->
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My app</title>
<script>
!function(w,d,o){if(w.userloop)return;var q=[],u=w.userloop={q:q};"init identify setAttributes track page show close reset setLanguage on off".split(" ").forEach(function(m){u[m]=function(){q.push([m,[].slice.call(arguments)])}});var s=d.createElement("script"),c=d.currentScript;s.async=1;s.src="https://cdn.userloop.io/sdk-3/userloop.js";if(c&&c.nonce)s.nonce=c.nonce;d.head.appendChild(s);u.init(o)}(window,document,{"siteKey":"SITE_KEY"});
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>Content-Security-Policy:
script-src 'nonce-RANDOM_PER_REQUEST' https://cdn.userloop.io;
connect-src https://s.userloop.io https://data.userloop.io https://survey-views.userloop.io;
img-src https: data:
<!-- Put the same nonce on the snippet. It passes it on to the scripts it loads. -->
<script nonce="RANDOM_PER_REQUEST">
!function(w,d,o){if(w.userloop)return;var q=[],u=w.userloop={q:q};"init identify setAttributes track page show close reset setLanguage on off".split(" ").forEach(function(m){u[m]=function(){q.push([m,[].slice.call(arguments)])}});var s=d.createElement("script"),c=d.currentScript;s.async=1;s.src="https://cdn.userloop.io/sdk-3/userloop.js";if(c&&c.nonce)s.nonce=c.nonce;d.head.appendChild(s);u.init(o)}(window,document,{"siteKey":"SITE_KEY"});
</script>Reference
Every method and every event
No method throws into your page. Calls made before the SDK has loaded are queued by the snippet and replayed in order.
- init(options)
- Starts the SDK. The snippet calls it for you, and only the first call on a page counts. Options: siteKey, storage, language, nonce, autoPageViews and debug.
- identify(userId, traits?)
- Sets your ID for the visitor, kept in the browser and sent with each answer. The trait email becomes the address the answers belong to. Other traits become attributes.
- setAttributes(attributes)
- Merges attributes into the visitor's. A new value replaces the old and null removes a key. Up to 50 keys. Every survey's rules are checked again.
- track(event)
- Opens surveys whose trigger is an event with this exact name, if their rules allow it now. It sends nothing anywhere.
- page()
- Counts a page view the SDK could not see. Time and scroll triggers start again and rules are checked against the current address.
- show(surveyId, options?)
- Opens a live website survey directly. Options include mode, position, target, force, firstAnswer and collectEmail.
- close(surveyId?)
- Closes the survey that is open, or every copy of the one you name. It fires no event.
- reset()
- For sign-out. A new visitor ID, and the user ID, email, attributes and survey history of this browser are forgotten.
- setLanguage(language)
- Fetches the site's surveys again in that language. An open survey changes language and keeps its answers.
- on(event, handler)
- Listens for an event. Once the SDK has loaded it returns a function that unsubscribes.
- off(event, handler)
- Stops listening, given the same event and handler.
- getVisitorId()
- The visitor ID, a random UUID sent with every answer. Available once the SDK has loaded.
- Event: shown
- The first question is visible, once per showing. For a feedback button, when the visitor first opens it. Payload: surveyId, responseId, mode.
- Event: answered
- The visitor gives an answer and moves on, and again if they change it. Payload: surveyId, responseId, questionId, questionType, final, and answerIds, text or score.
- Event: completed
- The last answer has been given. Payload: surveyId, responseId.
- Event: dismissed
- The visitor closed the survey before finishing. Not fired by close(). Payload: surveyId, responseId, answeredCount.
- Event: error
- Something failed, such as the site's surveys not loading or the browser refusing storage. Payload: code, and surveyId when one applies.
From your code
The calls you will write
Five short samples cover most installs: who the visitor is, when a survey opens, what happens on an answer, the same in React, and the types for all of it.
// When your app knows who is signed in. Call it on every page load.
userloop.identify("user_8421", {
email: "emma@example.com", // who the answers belong to, never an attribute
plan: "pro",
projects: 3,
});
// Attributes merge into what is set. null removes a key.
userloop.setAttributes({ beta: true, teams: ["design", "growth"] });
userloop.setAttributes({ beta: null });
// On sign-out: a new visitor ID, and the user, email and attributes forgotten
userloop.reset();// Your code decides: open one survey now.
// Skips its pages, visitor rules, share of visitors and trigger.
userloop.show("SURVEY_ID");
// A different look for this call only
userloop.show("SURVEY_ID", { mode: "slide_in", position: "bottom_left" });
// Inside an element of your page
userloop.show("SURVEY_ID", { mode: "inline", target: "#feedback" });
// Even if this visitor has already seen or answered it
userloop.show("SURVEY_ID", { force: true });
// Targeting decides: surveys whose trigger is "On an event" with this
// exact name open, if their other rules allow it for this visitor
userloop.track("signup_completed");
// Close the survey that is open
userloop.close();// With the loader snippet these can run before the SDK has loaded
userloop.on("shown", function (e) {
console.log("Shown", e.surveyId, e.mode);
});
userloop.on("answered", function (e) {
// One of answerIds, text or score, by question type
console.log(e.questionId, e.questionType, e.answerIds ?? e.text ?? e.score, e.final);
});
userloop.on("completed", function (e) {
console.log("Completed", e.surveyId, e.responseId);
});
userloop.on("dismissed", function (e) {
console.log("Closed after", e.answeredCount, "answers");
});
userloop.on("error", function (e) {
// site_fetch, storage, submit, render, renderer_load ...
console.warn("UserLoop", e.code, e.surveyId);
});// Call the SDK where something happens in your app
export function UpgradeButton() {
return (
<button
onClick={() => {
window.userloop?.track("upgrade_clicked");
}}
>
Upgrade
</button>
);
}
// Identify the signed-in user when your app knows who it is
import { useEffect } from "react";
export function UserLoopIdentity({ user }: { user: { id: string; email: string; plan: string } | null }) {
useEffect(() => {
if (user) window.userloop?.identify(user.id, { email: user.email, plan: user.plan });
}, [user]);
return null;
}
// In your sign-out handler:
// window.userloop?.reset();// src/userloop.d.ts. There is no npm package: declare the global once.
type UserLoopAttributes = Record<string, string | number | boolean | null | string[]>;
type UserLoopEvents = {
shown: { surveyId: string; responseId: string; mode: string };
answered: {
surveyId: string;
responseId: string;
questionId: string;
questionType: string;
answerIds?: string[];
text?: string;
score?: number;
final: boolean;
};
completed: { surveyId: string; responseId: string };
dismissed: { surveyId: string; responseId: string; answeredCount: number };
error: {
code: "site_fetch" | "document_fetch" | "invalid_document" | "storage" | "submit" | "render" | "renderer_load";
surveyId?: string;
};
};
type UserLoopShowOptions = {
mode?: "popup" | "slide_in" | "modal" | "feedback_button" | "inline";
position?: "bottom_right" | "bottom_left" | "top_right" | "top_left" | "center";
target?: string | Element;
force?: boolean;
respondent?: { email?: string };
firstAnswer?: string;
collectEmail?: boolean;
language?: string;
preview?: boolean;
};
interface UserLoop {
init(options: {
siteKey?: string;
storage?: "local" | "session" | "memory";
language?: string;
nonce?: string;
autoPageViews?: boolean;
debug?: boolean;
}): void;
identify(userId: string, traits?: UserLoopAttributes): void;
setAttributes(attributes: UserLoopAttributes): void;
track(event: string, properties?: UserLoopAttributes): void;
page(): void;
show(surveyId: string, options?: UserLoopShowOptions): void;
close(surveyId?: string): void;
reset(): void;
setLanguage(language: string): void;
/** Returns an unsubscribe function once the SDK has loaded; nothing before. */
on<E extends keyof UserLoopEvents>(event: E, handler: (payload: UserLoopEvents[E]) => void): (() => void) | undefined;
off<E extends keyof UserLoopEvents>(event: E, handler: (payload: UserLoopEvents[E]) => void): void;
/** Only once the SDK has loaded. */
getVisitorId?(): string | null;
/** Only once the SDK has loaded. */
readonly version?: string;
}
declare global {
interface Window {
userloop?: UserLoop;
}
}
export {};In the browser
What the SDK does with those calls
Rules are set in the dashboard and checked in the visitor's browser, so most changes need a publish and no deploy.
Targeting
Target by the attributes you set
Your app knows things UserLoop cannot see: the plan, the number of projects, whether a feature is on. Set them as attributes and a survey can be shown only to the visitors they describe.
Five rules. is, is not, contains, is set and isn't set. All of a survey's rules must hold. Two numbers compare as numbers, and text ignores capitals.
Checked again on every change. A survey waiting for its trigger starts or stops waiting as attributes change. Set them straight after the snippet.
Values and limits. A string, a number, true or false, or a list of strings. Up to 50 keys, with strings cut to 500 characters.
They are public. Rules travel with the page and attributes sit in the visitor's browser. Do not put private details in either.
Display
Five display modes, set once or per call
Each survey has its own mode from its Design stage. show() can override it for one call with mode and position.
popup. A card in bottom_right, bottom_left, top_right, top_left or center.
slide_in and modal. A panel that slides in at bottom_right or bottom_left, or a card in the center over a dimmed page.
feedback_button. A tab on the edge of the page. The survey counts as shown when a visitor opens it.
inline. Rendered in an element of your page, named by target. If nothing matches, an error event fires with the code render.
Single-page apps
Route changes followed, install confirmed
The SDK fetches the site's surveys once per page load and watches the History API. When the path or query changes, it counts a new page view without fetching again.
Nothing per route. pushState, replaceState, popstate and hashchange are watched. Next.js App Router, React Router and Vue Router all work this way.
Or drive it yourself. Set autoPageViews to false in the snippet's options and call page() after each route change.
Hash routers. The part of the address after # is never a new page view. Use an event trigger and track() from that route.
The dashboard checks. Check installation reads real page loads and shows Live with the address it saw. Pages on localhost never count.
Analytics
Survey events in GA4, with no extra code
Switch on the Google Analytics and Tag Manager integration and the SDK reports each survey event to the page's gtag or data layer. Nothing is configured on the page.
Four events. userloop_survey_shown, userloop_question_answered, userloop_survey_completed and userloop_survey_dismissed.
Parameters. survey_id, survey_title and response_id, plus question_id, answer and score where they apply.
Typed text stays out. A written answer, an email address, a phone number or a date is never sent. Chosen answers and scores are.
One route, not both. Turn on gtag or the data layer. A page with both counts each event twice. The integration is on Unlimited and Plus.
Privacy and performance
What it stores, what it loads and what it needs
No cookies
The visitor ID, attributes and survey history live in localStorage, and the visit in sessionStorage.
Three storage modes
local by default, session for one tab, or memory to keep nothing. A site that needs consent can start with memory.
Email stays in memory
The address from identify is never written to the browser's storage, so call identify on every page load.
Content Security Policy
One script source, three connect sources and images. No style, font or frame entry in current browsers.
13 KB loader
Gzipped, loaded asynchronously, so it does not hold up the page.
Renderer on demand
The 24 KB that draws a survey is fetched the first time one is about to show, never on a page that shows none.
Shadow DOM
A survey is drawn in its own shadow root, so your styles do not reach it and its styles do not reach your page.
Your site's addresses
List up to 20 and a copied snippet shows nothing on anyone else's site. localhost is always allowed for testing.
What it is not
A browser SDK, and only that
It runs in a web page. There is no npm package to install, no React or Vue component and no SDK for iOS or Android. The site key is public, so the SDK cannot read your responses: reading is the API's job. If you would sooner set surveys up without code, the website surveys page covers the same channel from the dashboard.
- None
- npm package
- None
- mobile SDKs
- Public
- site key, no secret
Frequently asked questions
Does UserLoop have a survey SDK?
Yes. The Web SDK is one script from UserLoop's CDN that shows website surveys and exposes window.userloop, with 12 methods and 5 events. It is on every plan, including Free.
Is there an npm package or a React component?
No. The SDK is a script tag, not a package, and there are no React or Vue components. In a framework you add the snippet once to the shared document and call window.userloop from your components. The docs give type declarations to paste into a .d.ts file.
Is there a mobile SDK for iOS or Android?
No. The SDK runs in web browsers only. For anywhere else, share a link survey, or collect answers in your own screens and record them with POST /responses through the API.
How big is the SDK?
The script on every page is 13 KB gzipped and loads asynchronously. The part that draws a survey is a further 24 KB, fetched only when a survey is about to show.
Does it work with Next.js, React and other single-page apps?
Yes. Add the snippet once, in app/layout.tsx with next/script or in index.html with Vite. The SDK watches the History API for route changes, so page rules keep working with no code per route.
How do I show a survey only to some users?
Call setAttributes with facts about the visitor, such as their plan, then add a visitor attribute rule on the survey's Targeting stage. A visitor can have up to 50 attributes, and every rule must hold for the survey to show.
Does the SDK set cookies?
No. It keeps the visitor ID, attributes and survey history in localStorage and the visit in sessionStorage. Set storage to session or memory in the snippet's options to keep less.
Does it work with a strict Content Security Policy?
Yes. Allow https://cdn.userloop.io in script-src, three UserLoop hosts in connect-src and images in img-src, and put a nonce on the snippet. The snippet passes the nonce on to the scripts it loads.
Can the SDK read my survey responses?
No. The site key in the snippet is public and grants nothing, so the SDK can only show surveys and send answers. To read responses, use the REST API with an API key from your server.
Keep reading
Paste one snippet and call userloop.show
The SDK is on the Free plan, which allows 1 live survey with 3 questions. Responses: 50 a month.