Can't import my env in my Function in Astro

Hello, I'm currently working on an Astro project and I'm trying to hide my API key using environment variables or secrets. However, when I attempt to import them into my code after publishing the page, it shows the error message:
"Cannot read properties of undefined (reading 'TEST')".
"Cannot read properties of undefined (reading 'TEST')".
I'm using Cloudflare SSR in a hybrid setup. Here's the code from my function:
export const prerender = false;

export async function GET(request, env, ctx) {
try {
const value = await env.TEST.get("STAGE_API_KEY");

if (value === null) {
return new Response("Value not found", { status: 404 });
}

return new Response(value);
} catch (e) {
return new Response(e.message, { status: 500 });
}
}
export const prerender = false;

export async function GET(request, env, ctx) {
try {
const value = await env.TEST.get("STAGE_API_KEY");

if (value === null) {
return new Response("Value not found", { status: 404 });
}

return new Response(value);
} catch (e) {
return new Response(e.message, { status: 500 });
}
}
If anybody has a solution to this issue, it would really help me out.
7 Replies
Hello, I’m Allie!
Have you defined the TEST vairable, either on the dashboard or in your wrangler.toml?
Bugeez
Bugeez4mo ago
Yes in the dashboard
Hello, I’m Allie!
Wait, is TEST a KV Namespace?
Bugeez
Bugeez4mo ago
Yes, I've defined it in my KV namespaces Binding looking for my KV namespace I was trying like this cuz i can't import the variable that i've set up in my Worker & Pages section
Hello, I’m Allie!
Try this:
export const prerender = false;

export function GET(context) {
try {
const value = await context.locals.runtime.TEST.get("STAGE_API_KEY");

if (value === null) {
return new Response("Value not found", { status: 404 });
}

return new Response(value);
} catch (e) {
return new Response(e.message, { status: 500 });
}
}
export const prerender = false;

export function GET(context) {
try {
const value = await context.locals.runtime.TEST.get("STAGE_API_KEY");

if (value === null) {
return new Response("Value not found", { status: 404 });
}

return new Response(value);
} catch (e) {
return new Response(e.message, { status: 500 });
}
}
Might also be context.locals.runtime.env.TEST
Bugeez
Bugeez4mo ago
For the first Version i've got this error :
Cannot read properties of undefined (reading 'get')
Cannot read properties of undefined (reading 'get')
And with the
context.locals.runtime.env.TEST
context.locals.runtime.env.TEST
: It worked ! Thx so much !
Hello, I’m Allie!
Yeah, the frameworks like doing their own thing
Want results from more Discord servers?
Add your server