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.Endpoint
Request
Headers
Must be set to
application/jsonBody Parameters
The subscriber’s email address. Must be a valid email format.
Request Example
Response
Success Response (200)
Indicates the subscription was successful
Human-readable success message
Example
Error Responses
400 Bad Request - Missing Email
Error message indicating missing or invalid email
400 Bad Request - Invalid Email Format
500 Internal Server Error - Beehiiv API Failure
500 Internal Server Error - General Error
Validation
The endpoint performs the following validations:- Email Presence: Checks that the
emailfield exists and is a string - 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:- A POST request is sent to Beehiiv’s subscription endpoint
- 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
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
Security Considerations
Best Practices
- Rate Limiting: Consider implementing rate limiting to prevent abuse
- CORS: Configure appropriate CORS policies if calling from external domains
- Input Sanitization: The endpoint validates email format but additional sanitization may be beneficial
- 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-Typeheader - Status Codes: 200 (success), 400 (validation error), 500 (server error)