You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js自定义表单集成Beehiiv API遇CORS错误求解决方案

解决Beehiiv订阅接口的CORS问题及API密钥安全风险

问题根源

直接在前端调用Beehiiv的API会触发CORS错误,因为Beehiiv的API服务器未配置允许你的前端域名跨域请求。此外,把API密钥写在前端代码里会直接暴露给用户,存在严重安全风险。

解决方案:使用Next.js API路由作为代理

通过Next.js的API路由在服务器端转发请求,既能解决CORS问题,又能安全存储API密钥。

步骤1:创建API路由

根据你的Next.js版本选择对应方式:

Pages Router(传统页面路由)

在pages/api目录下创建subscribe.js文件:

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: 'Method Not Allowed' });
  }

  const { email } = req.body;
  if (!email) {
    return res.status(400).json({ message: 'Please enter a valid email address.' });
  }

  try {
    const response = await fetch('https://api.beehiiv.com/v1/newsletter/subscribe', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.BEEHIIV_API_KEY}`,
      },
      body: JSON.stringify({ email }),
    });

    const data = await response.json();
    if (response.ok) {
      res.status(200).json({ message: 'Successfully subscribed! 🎉' });
    } else {
      res.status(response.status).json({ message: data.message || 'Something went wrong' });
    }
  } catch (error) {
    res.status(500).json({ message: 'Failed to subscribe. Please try again later.' });
  }
}

App Router(App目录路由)

在app/api/subscribe目录下创建route.js文件:

import { NextResponse } from 'next/server';

export async function POST(request) {
  const { email } = await request.json();
  if (!email) {
    return NextResponse.json(
      { message: 'Please enter a valid email address.' },
      { status: 400 }
    );
  }

  try {
    const response = await fetch('https://api.beehiiv.com/v1/newsletter/subscribe', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.BEEHIIV_API_KEY}`,
      },
      body: JSON.stringify({ email }),
    });

    const data = await response.json();
    if (response.ok) {
      return NextResponse.json({ message: 'Successfully subscribed! 🎉' });
    } else {
      return NextResponse.json(
        { message: data.message || 'Something went wrong' },
        { status: response.status }
      );
    }
  } catch (error) {
    return NextResponse.json(
      { message: 'Failed to subscribe. Please try again later.' },
      { status: 500 }
    );
  }
}

步骤2:配置环境变量

在项目根目录创建.env.local文件,添加你的Beehiiv API密钥:

BEEHIIV_API_KEY=你的实际API密钥

注意:不要把这个文件提交到版本控制系统(如Git),确保它在.gitignore列表中。

步骤3:修改前端模态框代码

更新handleSubscribe函数,改为调用自己的API路由,同时移除前端的Authorization头:

const handleSubscribe = async () => {
  if (!email) {
    setStatus('Please enter a valid email address.');
    return;
  }

  try {
    const response = await fetch('/api/subscribe', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email }),
    });

    const data = await response.json();
    if (response.ok) {
      setStatus(data.message);
      setEmail(''); // Clear input
    } else {
      setStatus(`Error: ${data.message || 'Something went wrong'}`);
    }
  } catch (error) {
    setStatus('Failed to subscribe. Please try again later.');
  }
};

额外注意事项

  • 确保你的Beehiiv API密钥具备执行订阅操作的权限。
  • 可在API路由中添加邮箱格式校验等额外逻辑,进一步提升安全性。

内容的提问来源于stack exchange,提问作者Deoxzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:50:16