How can I get environment variables in wasm js? I ...
# webassembly
s
How can I get environment variables in wasm js? I assume that accessing the js side of
process.env
is necessary, but the interop of the
js
function requires a static string, so I'm not seeing how to properly access it via js interop.
e
Copy code
fun getenv(name: String): String = js("process.env[name] ?? ''")
s
Thanks for the response! No matter what it's not happy though:
Copy code
fun getenv(name: String): String? {
    return js("process?.env?.[name]")
}
Copy code
Calls to 'js(code)' should be a single expression inside a top-level function body or a property initializer in Kotlin/Wasm.
This is just a function in a file, so I'm not seeing how we aren't meeting this criteria.
e
use
=
and I think
?
return doesn't work
m
I hope that doesn’t work for
wasmJs
😱
o
Here is how I've implemented it in ktor not so long ago
🙌 1
y
Did you find any solution? I have a same issue.
Copy code
// commonMain
expect val SERVER_DOMAIN: String


// wasmJsMain
actual val SERVER_DOMAIN: String
    get() {
        return js("process.env[KTOR_HOST]")
    }
Build Fail:
'js(code)' should be a single expression inside a top-level function body or a property initializer in Kotlin/Wasm.
e
it'll work with a wrapper, e.g.
Copy code
private fun getenv(name: String): String? = js("process.env[name]")
actual val SERVER_DOMAIN: String
    get() = getenv("KTOR_HOST")!!
y
oh.. you're right! compile error is solved! But... runtime error comes here ;;