Skip to main content

Overview

The Newsletter API allows users to subscribe to your newsletter through the Beehiiv platform. This endpoint validates email addresses and handles subscription requests with proper error handling.
This endpoint requires server-side configuration with Beehiiv API credentials. Ensure BEEHIIV_PUBLICATION_ID and BEEHIIV_API_KEY environment variables are properly set.

Endpoint

POST /api/newsletter
This is a server-rendered endpoint that processes newsletter subscription requests and communicates with the Beehiiv API.

Request

Headers

Content-Type
string
required
Must be set to application/json

Body Parameters

email
string
required
The subscriber’s email address. Must be a valid email format.

Request Example

curl -X POST https://yoursite.com/api/newsletter \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]"}'

Response

Success Response (200)

success
boolean
Indicates the subscription was successful
message
string
Human-readable success message

Example

{
  "success": true,
  "message": "Successfully subscribed! Check your email to confirm."
}

Error Responses

400 Bad Request - Missing Email

error
string
Error message indicating missing or invalid email
{
  "error": "Please provide an email address."
}

400 Bad Request - Invalid Email Format

{
  "error": "Please provide a valid email address."
}

500 Internal Server Error - Beehiiv API Failure

{
  "error": "Failed to subscribe. Please try again later."
}

500 Internal Server Error - General Error

{
  "error": "An error occurred. Please try again later."
}

Validation

The endpoint performs the following validations:
  1. Email Presence: Checks that the email field exists and is a string
  2. Email Format: Validates email format using regex pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
The email validation regex is intentionally simple and permissive. It checks for the basic email structure ([email protected]) but doesn’t enforce complex rules.

Beehiiv Integration

The endpoint integrates with the Beehiiv API to manage subscriptions. When a valid email is submitted:
  1. A POST request is sent to Beehiiv’s subscription endpoint
  2. The following parameters are configured:
    • reactivate_existing: false (won’t reactivate unsubscribed users)
    • send_welcome_email: true (sends confirmation email)
    • utm_source: “website” (tracks subscription source)
    • utm_medium: “organic” (tracks acquisition channel)

Beehiiv API Endpoint

POST https://api.beehiiv.com/v2/publications/{PUBLICATION_ID}/subscriptions

Error Handling

The endpoint implements comprehensive error handling:
  • Client-side validation errors (400): Return immediately with descriptive messages
  • Beehiiv API errors (500): Logged to console, generic error returned to client
  • Unexpected errors (500): Caught and logged, generic error returned to client
Error details from Beehiiv are logged server-side but not exposed to clients to prevent information leakage. Always check server logs for debugging subscription issues.

Security Considerations

API Key Protection: Never expose BEEHIIV_API_KEY or BEEHIIV_PUBLICATION_ID to the client. These are server-only environment variables.

Best Practices

  1. Rate Limiting: Consider implementing rate limiting to prevent abuse
  2. CORS: Configure appropriate CORS policies if calling from external domains
  3. Input Sanitization: The endpoint validates email format but additional sanitization may be beneficial
  4. Logging: Sensitive data (like full API errors) is logged server-side only

Implementation Details

  • Runtime: Server-side only (prerender: false)
  • HTTP Method: POST only
  • Response Type: Always JSON with appropriate Content-Type header
  • Status Codes: 200 (success), 400 (validation error), 500 (server error)

Example Integration

Here’s a complete example of integrating the newsletter API with a form:
<form id="newsletter-form">
  <input 
    type="email" 
    id="email" 
    placeholder="Enter your email"
    required 
  />
  <button type="submit">Subscribe</button>
  <div id="message"></div>
</form>

<script>
  const form = document.getElementById('newsletter-form');
  const emailInput = document.getElementById('email');
  const messageDiv = document.getElementById('message');

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const email = emailInput.value.trim();
    messageDiv.textContent = 'Subscribing...';
    
    try {
      const response = await fetch('/api/newsletter', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email })
      });

      const data = await response.json();

      if (response.ok) {
        messageDiv.textContent = data.message;
        messageDiv.style.color = 'green';
        form.reset();
      } else {
        messageDiv.textContent = data.error;
        messageDiv.style.color = 'red';
      }
    } catch (error) {
      messageDiv.textContent = 'Network error. Please try again.';
      messageDiv.style.color = 'red';
    }
  });
</script>

Build docs developers (and LLMs) love