我正在将 AWS Amplify 用于我的 Next.js 应用程序,并尝试与 Notion API 集成。在我的本地开发环境中,一切正常,并且可以通过环境变量正确访问 Notion 数据库 ID。但是,在 AWS Amplify 上的生产部署中,Notion 数据库 ID 的环境变量(例如 NEXT_NOTION_MARKETING_DATABASE_ID)显示为未定义。
这是我的相关coudwatch日志:
Error adding to Notion database: Error: NOTION_MARKETING_DATABASE_ID environment variable is missing.
这是我的相关客户端代码:
const handleSubscription = async () => {
if (!userOrg && !userLocation) {
handleIPRequest().catch((e) => {
e;
});
}
if (!subscriptionEmail) {
alert("Please enter a valid email");
return;
}
try {
const emailData: Record<string, string> = {
email: subscriptionEmail,
};
if (userOrg) {
emailData.organization = userOrg;
if (userLocation) {
emailData.location = userLocation;
}
}
const endpointUrl = `${process.env.NEXT_PUBLIC_FRONTEND_URL_PREFIX}/api/addSubscription`;
if (!endpointUrl) {
console.error(
"Environment variable NEXT_PUBLIC_FRONTEND_URL_PREFIX is missing.",
);
alert("Internal error. Please try again later.");
return;
}
const emailResponse = await axios.post(endpointUrl, emailData);
// Safeguard for missing status or malformed response
if (emailResponse.status === 200) {
console.log("Subscribed successfully:", emailResponse.data);
setOpenAlert(true);
setSubscriptionEmail(""); // Clear the email input field
// Automatically close the alert after 7 seconds
setTimeout(() => {
setOpenAlert(false);
}, 7000);
} else {
alert("Failed to subscribe. Please try again.");
console.error(
"Unexpected response:",
emailResponse.status,
emailResponse.data,
);
}
} catch (error) {
if (error instanceof Error) {
console.error("Subscription error:", error.message);
} else {
console.error("An unknown error occurred");
}
alert("An error occurred. Please try again later.");
}
};
这是我的服务器端代码:
import { Client } from "@notionhq/client";
import "dotenv/config";
// Initialize the Notion client with your integration token
const notion = new Client({ auth: process.env.NEXT_NOTION_API_TOKEN });
console.log(
process.env.NEXT_NOTION_MARKETING_DATABASE_ID,
process.env.NEXT_NOTION_BUSINESS_DATABASE_ID,
);
export async function POST(req) {
try {
// Parse the request body
const body = await req.json();
const email = body.email ?? null;
const organization = body.organization ?? "";
const location = body.location ?? "";
if (!email) {
return new Response(JSON.stringify({ message: "Email is required" }), {
status: 400,
});
}
// Get the current date in ISO 8601 format
const date = new Date().toISOString();
// Choose the correct Notion database based on the presence of `organization`
let databaseId;
if (organization) {
if (process.env.NEXT_NOTION_BUSINESS_DATABASE_ID) {
const businessID = process.env.NEXT_NOTION_BUSINESS_DATABASE_ID;
if (!businessID) {
throw new Error(
"NOTION_BUSINESS_DATABASE_ID environment variable is missing.",
);
}
databaseId = process.env.NEXT_NOTION_BUSINESS_DATABASE_ID;
}
} else {
const marketingID = process.env.NEXT_NOTION_MARKETING_DATABASE_ID;
if (!marketingID) {
throw new Error(
"NOTION_MARKETING_DATABASE_ID environment variable is missing.",
);
}
databaseId = process.env.NEXT_NOTION_MARKETING_DATABASE_ID;
}
console.log("Using Database ID:", databaseId);
// Add a new entry (page) to the Notion database
const notionResponse = await notion.pages.create({
parent: { database_id: databaseId },
properties: {
// "Name" is the title property, this is required in Notion
Name: {
title: [
{
text: {
content: email, // Using email as the title for this example
},
},
],
},
// The "Email" field as a string (email type)
Email: {
email: email, // Ensure email is passed as a plain string
},
// Add the "Location" field as a rich_text property
Location: {
rich_text: [
{
text: {
content: location,
},
},
],
},
// Add the "Date" field as a date property
Date: {
date: {
start: date, // Ensure the date is in ISO 8601 format
},
},
},
});
// Return a success response
return new Response(
JSON.stringify({ message: "Data added successfully", notionResponse }),
{
status: 200,
},
);
} catch (error) {
console.error("Error adding to Notion database:", error);
return new Response(
JSON.stringify({ message: "Error subscribing", error }),
{
status: 500,
},
);
}
}
这是我到目前为止所做的: 我已在 Amplify 控制台中的应用程序设置 > 环境变量下正确定义了环境变量。 添加/更新环境变量后,我重新部署了应用程序。 我检查了 CloudWatch 日志,显示变量丢失,即使它们是在 Amplify 环境中定义的。 我尝试过在代码中记录变量,但它们在生产中仍然未定义。
const marketingDatabaseId = process.env.NEXT_NOTION_MARKETING_DATABASE_ID;
我已经仔细检查了环境设置以获得正确的环境(生产)。
我已确认环境变量名称正确且区分大小写。
这个问题似乎是生产环境特有的,因为变量在本地开发中运行良好。
我有同样的问题,但你可以尝试在构建设置中编辑 amplify.yml,例如,如果你使用 npm
version: 1
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- echo "NEXT_NOTION_MARKETING_DATABASE_ID=$NEXT_NOTION_MARKETING_DATABASE_ID" >> .env
- echo "NEXT_NOTION_BUSINESS_DATABASE_ID=$NEXT_NOTION_BUSINESS_DATABASE_ID" >> .env
- npm run build
artifacts:
baseDirectory: .next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
- .next/cache/**/*
这就像一个魅力,您可以尝试来自 aws amplify 环境
的文档