Next.js Discord

Discord Forum

Function inside middleware always returns undefined

Answered
Keyhole wasp posted this in #help-forum
Open in Discord
Keyhole waspOP
function wtf(){
return "hello"
}

export async function middleware(request: NextRequest) {
console.log("hello") <-- this works
const hello = wtf()
console.log(hello) <-- this is undefined

I even tried moving the function inside of the middleware function, and still no dice
Answered by Keyhole wasp
Fixed. wtf was supposed to return an enum value (ie return myEnum.value1) and it kept returning undefined. Its because I was importing the enum from a "use client" file (I assumed it did some hoisting so the server could see everything at least). I moved the enum definition to its own separate file, and now it works.
View full answer

10 Replies

That's not true for that specific case you're providing as a reference:
Maybe the function you are trying to run is not compatible with the Edge runtime, APIs exclusive to Node.js runtime aren't supported in middleware.
@Keyhole wasp was it solved?
Keyhole waspOP
I have been working on another project the past day, but one thing that is different is that I al trying to return a value from a ts enum. Maybe middleware cant ise enums for some reason? Ill confirm in a bit
Its just a js object so it should work
Enums aren't "just a JS object" tho. I'm not sure if Middleware has an issue with them, but they're a TypeScript-specific feature, and actually, they're discouraged to use.
Keyhole waspOP
unlike other types in TS, TS just converts enums into objects so you can do things like enum ThingEnum{THING: "THING} and actually use it in code like return Thing
Enum.THING.
Well they will be discouraged to support only JS native features with [-erasableSyntaxOnly](https://www.totaltypescript.com/erasable-syntax-only) flag
Keyhole waspOP
Fixed. wtf was supposed to return an enum value (ie return myEnum.value1) and it kept returning undefined. Its because I was importing the enum from a "use client" file (I assumed it did some hoisting so the server could see everything at least). I moved the enum definition to its own separate file, and now it works.
Answer