admin管理员组

文章数量:1401673

How do you access environmental variables on edge runtime in NextJS using @cloudflare/next-on-pages? Right now I am using custom Cloudflare Worker deployed separately with the following code:

import Stripe from "stripe";

...

export default {
  async fetch(request: Request, env: {STRIPE_SECRET_KEY: string}): Promise<Response> {

    const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
        ...
      });
  },
};

I can access my stripe secret key using env.STRIPE_SECRET_KEY but is it possible to do something similar directly in NextJS server components prefixed with ' "const runtime="edge" ' ?

In my API route I have to call the Cloudflare Worker right now to access environmental variable which adds extra server calls:

import { NextResponse } from "next/server";
import { CheckoutApiRequest } from "@/types/api_types";

export const runtime = "edge";

export async function POST(req: Request) {
  try {
    const { amount } = (await req.json()) as CheckoutApiRequest;

    const res = await fetch("https://******", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ amount }),
    });
  
    if (!res.ok) {
      const error = await res.json();
      return NextResponse.json({ error }, { status: res.status });
    }
  
    const { sessionId } = await res.json();   
    return NextResponse.json({ sessionId: sessionId });
  } catch (error) {
    return NextResponse.json({
      error
    });
  }
}

本文标签: