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

NextJS中require关键字用法及Stripe代码等价写法问询

NextJS中Stripe require写法的等价替代方案

核心等价ES模块写法

const stripe = require('stripe')('some_key');的直接等价ES模块写法如下,适用于NextJS的API路由(服务器端环境):

import Stripe from 'stripe';
const stripe = new Stripe('some_key');

也可以简化成一行调用(Stripe导出的是可调用函数,两种写法效果一致):

import Stripe from 'stripe';
const stripe = Stripe('some_key');

把你原来的代码改成ES模块版本(适配NextJS Pages Router的API路由规范):

import Stripe from 'stripe';
const stripe = new Stripe('some_key');

export default async function handler(req, res) {
  if (req.method === 'POST') {
    // 验证用户身份逻辑
    const session = await stripe.billingPortal.sessions.create({
      customer: '{{CUSTOMER_ID}}',
      return_url: 'https://example.com/account',
    });

    res.redirect(session.url);
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

关于你用dynamic导入的错误

dynamic导入是NextJS用来延迟加载客户端组件的工具,而Stripe SDK必须在服务器端使用(不能把密钥暴露给客户端),所以完全没必要用dynamic导入Stripe实例。

你的错误写法里,dynamic() => import(('stripe')('some_key'))逻辑完全错误:import()只能接收模块路径字符串,不能直接调用模块函数。即使非要动态导入Stripe(完全没必要),正确写法也应该是:

import dynamic from 'next/dynamic';

const getStripe = async () => {
  const Stripe = (await import('stripe')).default;
  return new Stripe('some_key');
};

但再次强调:服务器端代码直接用普通import更简单、更安全。

内容的提问来源于stack exchange,提问作者engineer-x

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:25:14