newsletter-builder
  • Type to search the documentation.

Getting started

Quick start

Build an editor, save the document and send a compiled email in a few minutes.

1. Render the editor

components/editor.tsx
'use client'

import { useState } from 'react'
import {
  NewsletterBuilder,
  createWelcomeTemplate,
  type NewsletterDocument,
} from 'newsletter-builder-react'
import 'newsletter-builder-react/styles.css'

export function Editor() {
  const [doc, setDoc] = useState<NewsletterDocument>(() => createWelcomeTemplate())

  return (
    <div style={{ height: 'calc(100vh - 64px)' }}>
      <NewsletterBuilder initialDocument={doc} onChange={setDoc} />
    </div>
  )
}

2. Save the document

NewsletterDocument is plain JSON. Store it in a jsonb column or any document store and pass it back as initialDocument to continue editing. Use a key prop to remount the editor when you load a different document.

3. Compile on the server

app/api/send/route.ts
import { compileNewsletter } from 'newsletter-builder-react'

export async function POST(request: Request) {
  const { document, recipient } = await request.json()

  const { html, text, subject } = compileNewsletter(document, {
    variables: {
      firstName: recipient.firstName,
      unsubscribeUrl: `https://example.com/u/${recipient.token}`,
    },
  })

  await provider.send({ to: recipient.email, subject, html, text })
  return Response.json({ ok: true })
}

Always validate documents that arrive from clients. The compiler sanitises rich text and URLs, but you should still authorise who may send.