Collecting an email or SMS from a frontend website for subscribing to a newsletter or coupon code.
Exposing the REST API key publicaly is dangerous and not advised. Fortunately, our API allows you to create a user and a subscription without using the API key when identity verification is not enabled.
fetch(createUserAPI, {
method: "POST",
mode: "no-cors",
body: JSON.stringify({
subscriptions: [
{
type: "Email",
token: "[email protected]",
enabled: true,
},
],
}),
}),
Pass an array of Subscription objects to the Create User API to create a user who owns those subscriptions.
const payload = {
subscriptions: [
{
type: "Email",
token: "[email protected]",
enabled: true,
},
{
type: "SMS",
token: "+12345678901",
enabled: false,
},
]
}
- Set the subscription's
type
to Email or SMS. - The
token
must be valid for the giventype
, e.g., email subscriptions must use a valid email address. - Conditionally enable the subscription upon creation with
enabled
.
fetch(createUserAPI, {
method: "POST",
mode: "no-cors",
body: JSON.stringify({
subscriptions: [
{
type: "Email",
token: "[email protected]",
enabled: true,
},
],
}),
}),
const OoneSignalAppID = "<APP_ID>";
const createUserAPI = `https://api.onesignal.com/apps/${OoneSignalAppID}/users`;
const [error, _opaqueResult] = await safeTry(() =>
fetch(createUserAPI, {
method: "POST",
mode: "no-cors", // this is key if the customer doesn't control their server'
body: JSON.stringify({
subscriptions: [
{
type: "Email",
token: "[email protected]",
enabled: true,
},
],
}),
}),
);
if (error) {
console.error("Failed to create user");
} else {
// response is not useful because of no-cors mode
console.log("User created successfully");
}
If you have the ability to modify your server's CORS headers, allow our API https://api.onesignal.com
.
const [error, result] = await safeTry(() =>
fetch(createUserAPI, {
method: "POST",
body: JSON.stringify({
subscriptions: [
{
type: "Email",
token: "[email protected]",
enabled: true,
},
],
}),
}),
);
if (error) {
console.error("Failed to create user");
} else {
const { identity, subscriptions } = await result.json();
console.log("User created successfully");
console.log(`OneSignal ID: ${identity["onesignal_id"]}`);
console.log(`Subscription ID: ${subscriptions[0].id}`);
}
Utility code to make consuming our API result slightly nicer
const safeTry = async (fn) => {
try {
const result = await fn();
return [null, result];
} catch (e) {
if (e instanceof Error) {
console.error(e.message);
} else if (typeof e === "string") {
console.error(e);
} else {
console.error("An error occurred");
}
return [e, null];
}
};