Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,219 of 9,219 pages
About the help in other languages
All help pages

The newsletter on the GraphQL API

A headless front end (Next.js, Nuxt, Astro, an app) can offer the newsletter sign-up, the confirmation page and the unsubscribe page through the site's GraphQL API (/api/graphql) instead of the HTML pages of the site…

Download as PDF

Address: https://doc.exponential.earth/exphelp/viewer/ext/cjw_newsletter/graphql.md

On this page

The newsletter on the GraphQL API

A headless front end (Next.js, Nuxt, Astro, an app) can offer the newsletter sign-up, the confirmation page and the unsubscribe page through the site's GraphQL API (/api/graphql) instead of the HTML pages of the site. The same code serves the HTML form (newsletter/subscribe), so both channels check the same, answer the same and record the same consent.

1. Requirements

  • Exponential 6.0.15 or later (7.0.0 included) with the GraphQL API switched on (./console exp:graphql:enable) and its library webonyx/graphql-php. The extension adds its part of the schema through a schema extension with mutations (expGraphQLMutationExtension, new in 6.0.15); the version is not checked in code.
  • The newsletter's own event kinds (section 11) need a kernel with event kinds of packages (expGraphQLEventExtension). On a kernel without them, including earlier development builds of 6.0.15, the package loads and works as well, and its events are the kernel's mutation event instead.
  • At least one newsletter list named public (section 2) and a consent text (section 3). Without both, the schema has nothing of the newsletter.

2. Settings

settings/graphql.ini.append.php of the extension registers the schema extension ([GraphQLSettings] SchemaExtensionList[]=CjwNewsletterGraphQLExtension). Everything else is in cjw_newsletter.ini [GraphQLSettings], per siteaccess (settings/siteaccess/<siteaccess>/cjw_newsletter.ini.append.php) or for the whole installation (settings/override/):

[GraphQLSettings]
# the content object ids of the lists the API offers in this siteaccess; empty (the default): none
PublicListList[]=123
# where the mails of an API sign-up link to; {hash} is the person's hash. Empty: the site's newsletter/configure page
ConfirmUrl=https://front.example.org/newsletter/confirm/{hash}
# sign-ups per caller (IP address, user or API key) and window in seconds; 0 switches a limit off
SubscribeLimitPerClient=10
SubscribeLimitPerClientWindow=3600
# opt-in and information mails per address and window (the HTML form counts these too)
SubscribeLimitPerAddress=3
SubscribeLimitPerAddressWindow=86400
# confirm and unsubscribe calls per caller and window
HashLimitPerClient=30
HashLimitPerClientWindow=3600

A list is offered only when it is named in PublicListList[], a consent text applies to it, and the caller may read its content object and holds the policy newsletter/subscribe. A list that is named but has no consent text is left out, with a warning in the log that names the list and the missing setting.

ConfirmUrl must be an https: address with {hash} in it; any other value is ignored with a warning in the log, and the mails link to the site. It is used only for the mails of a sign-up through the API; the HTML form keeps linking to the site.

After a change of the settings, clear the INI cache (php bin/php/ezcache.php --clear-tag=ini).

See the README, "Consent text and version". newsletterLists answers the text and version that apply to each list; the front end shows exactly that text and names its version in newsletterSubscribe. A sign-up that names another version than the current one is refused with BAD_USER_INPUT, which names the current version, so a front end that cached an old text cannot record consent to a text nobody showed.

What is recorded: the version and the channel (graphql or form) on every subscription the sign-up creates (cjwnl_subscription.consent_version, consent_channel, shown on the subscription page of the administration), and, with the kernel's e-mail preferences, a row in the consent log with the source signup, the action pending and the wording <text> [consent version <version>, <channel>]. The confirmation and the unsubscribe are recorded as before (source bridge).

4. Schema

type NewsletterList { id: Int! name: String! description: String outputFormats: [NewsletterOutputFormat!]!
                      interests: [NewsletterInterest!]! consent: NewsletterConsent! }
type NewsletterOutputFormat { id: Int! name: String! }
type NewsletterInterest { id: Int! name: String! }
type NewsletterConsent { version: String! text: String! }
enum NewsletterSignupStatus { ACCEPTED SUBSCRIBED }
type NewsletterSignupPayload { status: NewsletterSignupStatus! }
type NewsletterConfirmPayload { status: String! listIds: [Int!]! }      # CONFIRMED
type NewsletterUnsubscribePayload { status: String! }                    # UNSUBSCRIBED
input NewsletterListChoice { listId: Int! outputFormatIds: [Int!] }

extend type Query { newsletterLists: [NewsletterList!]! }
extend type Mutation {
  newsletterSubscribe(email: String!, lists: [NewsletterListChoice!]!, consentVersion: String!,
                      interestIds: [Int!], salutation: Int, firstName: String, lastName: String): NewsletterSignupPayload
  newsletterConfirm(hash: String!): NewsletterConfirmPayload
  newsletterUnsubscribe(hash: String!): NewsletterUnsubscribePayload
}

id is the content object id of the list, name its name, description its short description as plain text. The payloads of the mutations are nullable, as the kernel's: in a request with several mutations, one that fails answers null with its error and the others keep their answers.

5. Answers

MutationAnswerErrors (extensions.code)
newsletterSubscribeACCEPTED: an opt-in mail goes to a new address, an information mail with the configure link to a known one, nothing to a blacklisted or suppressed address or one over its limit. SUBSCRIBED: the own account address of a signed-in caller, subscribed at once without mail.BAD_USER_INPUT: invalid address, no list, a list that is not offered, an output format or interest the lists do not offer, a consent version that is not the current one (the message names the value). RATE_LIMITED: the caller is over its limit (the message names the seconds to wait).
newsletterConfirmCONFIRMED and the ids of the public lists the person is subscribed to now. A second call answers the same.NOT_FOUND: unknown hash, blacklisted or removed person. RATE_LIMITED.
newsletterUnsubscribeUNSUBSCRIBED, also when the subscription has ended already.NOT_FOUND: unknown hash, blacklisted or removed person. RATE_LIMITED.

All three: DISABLED when mutations are switched off in the siteaccess (the mutations are then not in the schema), BAD_USER_INPUT for a GET, FORBIDDEN for an API key without graphql:write, a session request without its form token (X-CSRF-Token), or a caller without the newsletter policy of the page the mutation replaces (newsletter/subscribe, newsletter/configure, newsletter/unsubscribe).

The answer of newsletterSubscribe is the same for every address. The input is checked completely before the address is looked up, so a known and a new address get the same errors for the same input, and a valid sign-up answers ACCEPTED whatever the address's state. A known person's subscriptions, name and interests are never changed by a sign-up; the configure page does that.

6. Who may call: anonymous callers

The newsletter mutations change no content, work only on the public lists, are limited and answer the same for every address. Their own guard (CjwNewsletterGraphQLGuard) therefore applies every rule of the kernel's mutations (off, GET, API key scope, session form token) except the one that refuses anonymous callers unless graphql.ini [GraphQLSettings] AnonymousMutations=enabled, a switch that opens every content mutation to the role Anonymous.

Exponential 6.0.15 and the end point. The kernel's end point checks every mutation operation with its own rules before any resolver runs. In 6.0.15 that check refuses an anonymous mutation operation unless AnonymousMutations is on, so an anonymous newsletterSubscribe sent straight to /api/graphql is refused with FORBIDDEN there. The extension names its mutations that are open to anonymous callers (anonymousMutationFields()); a kernel that lets an extension do so passes them on. Until then, use one of these:

  • A server-side call with a personal API key (recommended): the front end's server (a Next.js route handler, a Nuxt server route) calls the API with an API key with the scope graphql:write of a user that holds the newsletter policies. The sign-up of a visitor's address is then a signed-in sign-up of another address: pending, with the opt-in mail, ACCEPTED. The per-client limit counts the key, so raise SubscribeLimitPerClient for it and keep the per-address limit; the front end's server should limit per visitor itself.
  • AnonymousMutations=enabled, only if the role Anonymous may create, edit or remove no content anywhere.

7. Examples

List the public lists:

curl -s https://www.example.org/api/graphql -H 'Content-Type: application/json' \
     -d '{"query":"{ newsletterLists { id name description outputFormats { id name } interests { id name } consent { version text } } }"}'
{"data":{"newsletterLists":[{"id":123,"name":"News","description":"Once a month.","outputFormats":[{"id":0,"name":"html"}],
 "interests":[],"consent":{"version":"1","text":"Yes, I would like to receive the newsletter by e-mail. ..."}}]}}

Sign up (here with a personal API key, from the front end's server):

curl -s https://www.example.org/api/graphql -H 'Content-Type: application/json' -H "Authorization: Bearer $EXP_API_KEY" \
     -d '{"query":"mutation ($email: String!, $version: String!) { newsletterSubscribe(email: $email, lists: [{listId: 123}], consentVersion: $version) { status } }",
          "variables":{"email":"[email protected]","version":"1"}}'
{"data":{"newsletterSubscribe":{"status":"ACCEPTED"}}}

The same from a front end, with fetch:

const query = `mutation ($email: String!, $lists: [NewsletterListChoice!]!, $version: String!) {
  newsletterSubscribe(email: $email, lists: $lists, consentVersion: $version) { status } }`;
const answer = await fetch('https://www.example.org/api/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.EXP_API_KEY}` },
  body: JSON.stringify({ query, variables: { email, lists: [{ listId: 123 }], version: consent.version } }),
}).then((r) => r.json());
if (answer.errors) showError(answer.errors[0].message);   // BAD_USER_INPUT, RATE_LIMITED ...
else showThankYou();                                       // ACCEPTED: "please confirm the link in your mail"

Confirm and unsubscribe:

mutation { newsletterConfirm(hash: "0123456789abcdef0123456789abcdef") { status listIds } }
mutation { newsletterUnsubscribe(hash: "fedcba9876543210fedcba9876543210") { status } }

8. Confirmation and unsubscribe pages of a front end

  • Confirmation: with ConfirmUrl=https://front.example.org/newsletter/confirm/{hash}, the opt-in mail of an API sign-up links there (and so does the information mail a known address gets). The page reads the hash from its path, calls newsletterConfirm(hash:) and shows the answer: CONFIRMED (with the lists), or a "this link is not valid" page for NOT_FOUND. Changing the lists, the name or the interests stays on the site's configure page (/newsletter/configure/<hash>), which the front end can link to.
  • Unsubscribe: the links in the newsletters themselves point to the site (/newsletter/unsubscribe/<hash>), and the one-click unsubscribe of mail programs (RFC 8058, a POST) goes to the site as well. A front end that serves its own page reads the hash, asks the reader to confirm, and calls newsletterUnsubscribe(hash:).

9. Limits

Besides the kernel's request limits (graphql.ini RateLimit, RateLimitAnonymous):

  • per caller (an anonymous one by its IP address, a signed-in one by its user or API key): SubscribeLimitPerClient sign-ups and HashLimitPerClient confirm/unsubscribe calls per window; over it, RATE_LIMITED and nothing is stored or sent;
  • per address: SubscribeLimitPerAddress opt-in and information mails per window, through the API and the HTML form together; over it, no further mail, and the answer stays ACCEPTED.

The counters are files under var/cache/graphql/rate/ (the kernel's rate limiter), named by a hash: an address is never a file name. Several web servers without a shared var/ count separately, as the kernel's own limits do. Without the kernel's GraphQL classes (an older kernel) the HTML form has no address limit.

10. Audit

Each newsletter mutation is recorded in the audit as system.cjw_newsletter.graphql.mutation (the mutation, how the caller signed in, the list ids, the answer), a refusal or an error as system.cjw_newsletter.graphql.mutation.failed with its reason. Never the address, the names or the hash.

11. Events: webhooks and subscriptions

A subscription that becomes active (confirmed by the person or approved), and one that is removed by the person or an administrator, through any channel (the site's pages, the API, the administration, mail-in), is written to the kernel's GraphQL event journal with the content object id of the list. The kernel adds the list's class and locations. The event names the list, never the person. An import writes no events.

The newsletter's own event kinds

A schema extension of its own, CjwNewsletterGraphQLEventKinds (listed in the extension's settings/graphql.ini.append.php), declares two event kinds of the package (expGraphQLEventExtension::eventKinds()) on a kernel that has event kinds of packages; on an older kernel it loads as well and declares nothing:

KindEnum value (subscriptions)WhenFields (data)
newsletter.subscription.confirmednewsletter_subscription_confirmeda subscription became confirmed or approvedlistId (int), status (confirmed, approved)
newsletter.unsubscribednewsletter_unsubscribeda confirmed or approved subscription was removedlistId (int), status (removed_self, removed_admin)

Both are bound to the list's content object: a subscriber hears them only while they may read the list. The kinds are known in a siteaccess while the extension is available there, that is while PublicListList[] names a list.

A webhook gets them only when its Events[] names them, one by one or as newsletter.* (an end point without Events[] gets the core kinds only). The kind is in the header X-Exponential-Event and the fields in data:

[GraphQLWebhook_crm]
URL=https://crm.example.org/hooks/newsletter
Events[]=newsletter.*
ClassList[]=cjw_newsletter_list

A subscription (/api/graphql/subscribe) names them in its enum form:

subscription {
  contentEvents(events: [newsletter_subscription_confirmed, newsletter_unsubscribed]) {
    event objectId time data { name value }
  }
}

Without the kinds: the mutation event

Where the kinds are not registered (a kernel without event kinds of packages, or no list is public in the siteaccess) the same changes are written as the kernel's event mutation, with the mutation name newsletterSubscriptionConfirmed or newsletterUnsubscribed and the list's object id, and no data:

[GraphQLWebhook_crm]
URL=https://crm.example.org/hooks/newsletter
Events[]=mutation
ClassList[]=cjw_newsletter_list
subscription { contentEvents(events: [mutation]) { event mutation objectId time } }

Each change is written once, in one of the two forms, never both.

Something wrong on this page? Report an error

Documentation license

This page is part of the documentation of the extension cjw_newsletter and is distributed under the license of that extension.