@@ -8,6 +8,11 @@ export const runtime = 'nodejs';
88// Force dynamic to prevent aggressive caching
99export const dynamic = 'force-dynamic' ;
1010
11+ // IMPORTANT: For Amplify Hosting inconsistencies with runtime env injection, we inline
12+ // the secret at build time by reading from .env during build. Amplify writes .env in amplify.yaml.
13+ // This results in the value being embedded in the server bundle similarly to a Lambda env var.
14+ const DB_URI = process . env . MONGO_URI as string | undefined ;
15+
1116// Reuse a cached connection across hot reloads / lambda invocations to avoid creating many sockets.
1217declare global {
1318 // eslint-disable-next-line no-var
@@ -28,8 +33,6 @@ async function connectToDatabase(uri: string) {
2833
2934// Handle POST request to save a score
3035export async function POST ( req : Request ) {
31- const DB_URI = process . env . MONGO_URI ; // read at request time to avoid build-time inlining issues
32- console . log ( 'POST /api/scores - MONGO_URI present:' , ! ! DB_URI , 'length:' , DB_URI ?. length || 0 ) ;
3336 if ( ! DB_URI ) {
3437 return NextResponse . json ( { error : 'Server not configured (MONGO_URI missing)' } , { status : 503 } ) ;
3538 }
@@ -41,7 +44,7 @@ export async function POST(req: Request) {
4144 if ( typeof score !== 'number' || ! Number . isFinite ( score ) || score < 0 ) {
4245 return NextResponse . json ( { error : 'Invalid score' } , { status : 400 } ) ;
4346 }
44- await connectToDatabase ( DB_URI ) ;
47+ await connectToDatabase ( DB_URI ) ;
4548 const newScore = new Score ( { name : name . trim ( ) , score : Math . floor ( score ) } ) ;
4649 await newScore . save ( ) ;
4750 return NextResponse . json ( { message : 'Score saved' , score : newScore } , { status : 201 } ) ;
@@ -53,8 +56,6 @@ export async function POST(req: Request) {
5356
5457// Handle GET request to fetch all scores
5558export async function GET ( ) {
56- const DB_URI = process . env . MONGO_URI ; // read at request time
57- console . log ( 'GET /api/scores - MONGO_URI present:' , ! ! DB_URI , 'length:' , DB_URI ?. length || 0 ) ;
5859 if ( ! DB_URI ) {
5960 return NextResponse . json ( { error : 'Server not configured (MONGO_URI missing)' } , { status : 503 } ) ;
6061 }
0 commit comments