https://kotlinlang.org logo
Join Slack
Powered by
# javascript
  • e

    Edoardo Luppi

    08/09/2025, 4:00 PM

    https://youtu.be/z-u99yZFn5o?t=767▾

    That was an interesting watch. And the
    Long
    issue is now pretty much resolved with
    bigint
    . Tho @Arkadii Ivanov I'm curious to understand why you guys think annotating declaration isn't ideal. Which kind of solution would you prefer? Gradle-based to mass export?
    a
    • 2
    • 6
  • r

    rnett

    08/10/2025, 12:52 AM
    I'm getting an error when
    :kotlinWasmNpmInstall
    and
    :kotlinNpmInstall
    run at the same time. https://scans.gradle.com/s/clmy5234k76zi Is this a known issue? Or is there anything I can do about it?
    t
    c
    v
    • 4
    • 6
  • n

    neworldlt

    08/11/2025, 2:12 PM
    Sorry for the noob question, but what Node.js version should I use? The KMP curated version is quite old, v22.0.0 and without patches. Is it just the oldest version KMP supports, or a preferable one? I am using NodeJS just for builds, so security is less of a concern.
    a
    e
    j
    • 4
    • 19
  • e

    Eugene Maksymenko

    08/12/2025, 10:08 AM
    Powerful optimization of the first KMP 3D Globe engine WorldWind Kotlin v1.8.2 released https://github.com/WorldWindEarth/WorldWindKotlin/releases/tag/v1.8.2
    🚫 2
    g
    • 2
    • 1
  • m

    MrPowerGamerBR

    08/19/2025, 5:38 PM
    In Kotlin/JS, how can I initialize a JavaScript Integer? I'm creating typings for a library (Discord Embedded App SDK) and to set an activity they have a
    Timestamps
    object that expects two integers: A
    start
    and
    end
    timestamps. These timestamps are Epoch millis. The library expects integers for these timestamps: https://discord.com/developers/docs/events/gateway-events#activity-object-activity-timestamps But that's where the issue lies: I can't figure out a way to initialize a JavaScript Integer! • A Kotlin Int doesn't work because converting a epoch millis to a Kotlin Int causes it to overflow and go into the negatives • A Kotlin Long doesn't work due to the way Kotlin Long works in Kotlin/JS • A Kotlin BigInt doesn't work because the backend (in this case, Discord's RPC protocol) complains that it isn't a number • A Kotlin String doesn't work because the backend complains that it isn't a number The only way I found to make it work is by initializing the number via
    js
    , but I wonder if there's a better way to do this?
    Copy code
    discordSDK.commands.setActivity(
                            SetActivityRequest(
                                activity = Activity(
                                    0, // Changes the top of the activity title in the profile
                                    "PixelBloom",
                                    "Placing pixels at ${cursor.value?.x}, ${cursor.value?.y}",
                                    timestamps = Timestamps(
                                        start = js("new Date().getTime()")
                                    )
                                ).also {
                                    console.log("Generated Activity: ", it)
                                }
                            )
                        )
    b
    e
    +2
    • 5
    • 9
  • p

    phteven

    08/20/2025, 2:19 PM
    I cannot see the green arrows anymore in a kotlin js test file to run tests from intellij. Also right click on test folder does not show any run test actions. Kotlin 2.2.0, multiplatfor gradle plugin, karma test. Running the gradle task is the only way to do it for me. I remember in the past this was working 🤔
    t
    l
    • 3
    • 5
  • p

    phteven

    08/21/2025, 2:52 PM
    Running
    ./gradlew jsBrowserDevelopmentRun -t
    always refreshes my browser page twice. On save on on compile. Is it possible to configure some debounce here?
    c
    t
    • 3
    • 2
  • p

    PHondogo

    08/22/2025, 2:17 PM
    I've noticed that production executable js file (generated by jsBrowserDistribution task) is not obfuscated (has original class/function/variable names) and contains embedded source map (sourceMappingURL=data:application/json;...) Is it a bug or i should configure Gradle build somehow? I'm using Kotlin 2.2.20-RC
    l
    • 2
    • 1
  • r

    Robert Jaros

    08/24/2025, 2:01 PM
    Anyone else is experiencing webpack production task not being executed? Even after clean build the
    jsBrowserProductionWebpack
    task is somehow skipped.
    p
    • 2
    • 8
  • c

    CLOVIS

    08/25/2025, 7:00 AM
    Vite for Kotlin 0.6.0 is out! This version adds the options
    server.host
    ,
    server.port
    ,
    server.strictPort
    and
    server.proxy
    . The documentation is now available at https://vite-kotlin.opensavvy.dev
    👍 5
  • p

    Phil Kagebein

    08/26/2025, 9:35 PM
    I am working on upgrading our kotlin version from
    2.1.20
    ->
    2.2.10
    . Previously, we used
    KtMap.getInstance().fromJsMap()
    to convert a JS Map to a Kotlin map so that the client can send some data back to KM. However, in
    2.2.10
    getInstance()
    is not available anymore. Is there a more preferred way to do these sorts of operators for objects like
    KtMap
    or
    KtList
    ?
    e
    a
    • 3
    • 4
  • p

    PHondogo

    08/29/2025, 8:42 AM
    When generating Javascript binaries in dist/js folder i see *.mjs files that are never used/downloaded when browsing app. Why are they needed? Is it safe to remove them from distribution? Kotlin 2.2.20-Beta2 Compose 1.9.0-rc01
    a
    i
    e
    • 4
    • 14
  • r

    Robert Jaros

    08/31/2025, 8:33 AM
    Anyone using
    2.2.20-Beta2+
    please check: https://kotlinlang.slack.com/archives/C0KLZSCHF/p1756626364165389
  • s

    Stefan Oltmann

    08/31/2025, 10:23 AM
    In a Cloudflare Worker I want to verify a JWT token. I saw that the awesome
    kotlin-wrappers
    project has already wrappers for that, but I lack sample code how to use it. I find it hard to use it without docs & samples. This is the original JavaScript I want to translate:
    Copy code
    async function verifyJwt(token, publicKeyBase64Der) {
    
        const parts = token.split('.');
    
        if (parts.length !== 3)
            throw new Error("JWT malformed");
    
        const [headerBase64, payloadBase64, signatureBase64] = parts;
    
        const signature = base64urlToUint8Array(signatureBase64);
        const data = new TextEncoder().encode(headerBase64 + '.' + payloadBase64);
        const headerJson = JSON.parse(utf8Decode(base64urlToUint8Array(headerBase64)));
    
        if (headerJson.alg !== "ES256")
            throw new Error("Unsupported Algorithm: " + headerJson.alg);
    
        const keyData = base64ToUint8Array(publicKeyBase64Der);
    
        const cryptoKey = await crypto.subtle.importKey(
            "spki",
            keyData,
            {
                name: "ECDSA",
                namedCurve: "P-256",
            },
            false,
            ["verify"]
        );
    
        const verified = await crypto.subtle.verify(
            {name: "ECDSA", hash: "SHA-256"},
            cryptoKey,
            signature,
            data
        );
    
        if (!verified)
            throw new Error("Invalid signature");
    
        return JSON.parse(utf8Decode(base64urlToUint8Array(payloadBase64)));
    }
    ✅ 1
    a
    • 2
    • 9
  • s

    Stefan Oltmann

    08/31/2025, 12:32 PM
    Did someone ever used a Cloudflare R2 bucket from a Cloudflare worker in Kotlin/JS? I wonder how that is defined.
    c
    • 2
    • 7
  • h

    Horatio Thomas

    08/31/2025, 12:51 PM
    anyone aware of any examples like this using ktor instead of spring https://github.com/Kotlin/kmp-spring-petclinic/?
    b
    • 2
    • 2
  • s

    Stefan Oltmann

    09/01/2025, 8:34 AM
    I'd like people with a good Cloudflare and Kotlin/JS understanding to review (or contribute to) my new project: https://github.com/StefanOltmann/cloudflare-steam-name-update-service I think a lot can be improved here. Especially how I pass in the environment - didn’t find a better way. And I don't like all the
    js()
    interop, too. I like this to be Kotlin/WASM, but the sample (a fork from the original hello world) I found was outdated and didn't work for me. So I appeciate if you drop me hints how to improve or helpful ressources (like sample code) how to properly work with Kotlin/JS (or even better Kotlin/WASM) on Cloudflare Workers. 🙂
    👀 2
    K 1
    t
    • 2
    • 98
  • e

    Edoardo Luppi

    09/01/2025, 3:15 PM
    As far as I recall, there was some talk about un-deprecating the
    @EagerInitialization
    annotation. If that is the case: 1. could it be also applicable to top-level functions? This would be useful for code that has to run when the JS module is initialized. The current workaround is a property that calls a function. 2. could we instead move to an annotation that starts with
    @Js*
    to streamline the naming? For example
    @JsEager
    or
    @JsImmediate
    .
  • g

    grahamborland

    09/02/2025, 11:12 PM
    Trying to upgrade Kotlin from 2.2.0 -> 2.2.10 and started getting this error:
    Copy code
    Execution failed for task ':kotlinNpmInstall'.
    >                 Process 'Resolving NPM dependencies using yarn' returns 1
                      Unknown Syntax Error: Unsupported option name ("--network-concurrency").
    Any workaround?
    v
    e
    a
    • 4
    • 10
  • c

    CLOVIS

    09/03/2025, 7:47 PM
    What would be the correct way to add a dependency if the user has configured a specific feature? For example, I need a specific dependency if the user has defined
    useCommonJs()
    . To detect that, I'm using:
    Copy code
    val moduleKind = project.objects.property<JsModuleKind>()
    	project.tasks.withType<org.jetbrains.kotlin.gradle.targets.js.ir.KotlinJsIrLink> {
    		moduleKind.set(compilerOptions.moduleKind)
    	}
    but by the time
    moduleKind
    is set, it's not allowed to add a
    implementation(npm("foo", "1.0.0"))
    anymore. I've also tried having a
    : RequiresNpmDependencies
    task with a dependency set that changes once
    moduleKind
    is known, and that works without the configuration cache, but with it I get a serialization crash within the configuration cache itself.
    e
    v
    +2
    • 5
    • 30
  • j

    jamshedalamqaderi

    09/04/2025, 9:59 AM
    How can I achieve lazy loading to reduce initialize time of any kotlin js browser app?
    a
    t
    • 3
    • 5
  • t

    Tristan

    09/04/2025, 6:17 PM
    Hello, I have a library that targets both Android and Js. It uses Metro for DI. I compile with
    jsBrowserProductionLibraryDistribution
    Copy code
    js {
            moduleName = project.name
            useEsModules()
            binaries.library()
        }
    I have the following code
    Copy code
    @Inject
    internal class InvocationHandler(
        private val exposedFunctions: Map<String, Provider<ExposedFunction>>,
    ) {
        operator fun invoke(
            onInvocations: SharedFlow<Invocation>,
        ): Flow<Invocation> {
            return onInvocations
                .onEach {
                    val exposedFunction = exposedFunctions[it.location] ?: return@onEach
    
                    it.handle {
                        val fn = exposedFunction()
                        fn(it.parameters) // This throws an error on JS
                    }
                }
        }
    }
    
    // ...
    
    @Inject
    @ContributesIntoMap(AppScope::class)
    @ExposedAtLocation(ExposedFunctionLocation.IS_FILE_CACHED)
    internal class IsFileCached(private val cacheRepository: CacheRepository) : ExposedFunction {
        override suspend fun invoke(args: List<Any>): Any {
            val fileUrl = args[0] as? String ?: return false
            return cacheRepository.isCached(fileUrl)
        }
    }
    For the code above, I will get
    Copy code
    TypeError: fn is not a function
    And if I print with
    fn.toString
    Copy code
    function (_this__u8e3s4, $completion) {
        return i.v8b(_this__u8e3s4, $completion);
      }
    Do you know what could cause this issue?
    a
    e
    z
    • 4
    • 36
  • c

    CLOVIS

    09/05/2025, 6:32 PM
    I'm getting this weird import in the generated
    kotlin-kotlin-stdlib.js
    Copy code
    const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
    const HELPERS_ID = '\0commonjsHelpers.js';
    Note the
    \0
    . Has anyone seen this before?
    e
    • 2
    • 10
  • a

    Alex Styl

    09/09/2025, 4:13 AM
    Im getting an error
    Could not locate the bindings file
    when I am installing
    sqlite3
    as a npm() dependnecy in build.gradle.kts:
    Copy code
    implementation(npm("sqlite3",  "5.1.7"))
    I think it has something to do with native bindings (C ?) . The library is this one Any pointers on how to use it in kotlin /js ?
    a
    i
    • 3
    • 10
  • c

    Cas Van Luijtelaar

    09/09/2025, 7:22 AM
    running into
    Copy code
    e: org.jetbrains.kotlin.util.FileAnalysisException: Somewhere in file /Users/casvanluijtelaar/Projects/***/deals/DealsOfferKey.kt: java.lang.NullPointerException: null cannot be cast to non-null type org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
    	at org.jetbrains.kotlin.util.AnalysisExceptionsKt.wrapIntoFileAnalysisExceptionIfNeeded(AnalysisExceptions.kt:62)
    	at org.jetbrains.kotlin.fir.FirCliExceptionHandler.handleExceptionOnFileAnalysis(Utils.kt:251)
    	at org.jetbrains.kotlin.fir.resolve.transformers.FirSupertypeResolverTransformer.transformFile(FirSupertypesResolution.kt:892)
    	at org.jetbrains.kotlin.fir.declarations.FirFile.transform(FirFile.kt:46)
    	at org.jetbrains.kotlin.fir.resolve.transformers.FirTransformerBasedResolveProcessor.processFile(FirResolveProcessor.kt:48)
    	at org.jetbrains.kotlin.fir.resolve.transformers.FirTotalResolveProcessor.process(FirTotalResolveProcessor.kt:36)
    	at org.jetbrains.kotlin.fir.pipeline.AnalyseKt.runResolution(analyse.kt:24)
    	at org.jetbrains.kotlin.fir.pipeline.FirUtilsKt.resolveAndCheckFir(firUtils.kt:76)
    when I try to build
    jsBrowserDevelopmentLibraryDistribution
    seems to throw on any file with kotlinx-serializable imported. e.g. this file only contains:
    Copy code
    import kotlinx.serialization.Serializable
    
    @Serializable
    data class DealsOfferKey(
        val offerId: Int,
        val offerInstanceUniqueId: String?,
    )
    removing the annotation and the import fixes the issue. but then errors on one of a million other files with serializable included. Anyone seen this before?
    e
    a
    • 3
    • 7
  • e

    Edoardo Luppi

    09/10/2025, 8:55 AM
    2.2.20 is out, and there are a lot of improvements for JS. https://github.com/JetBrains/kotlin/releases/tag/v2.2.20
  • e

    Edoardo Luppi

    09/10/2025, 9:51 AM
    Just an observation now that I've compiled with 2.2.20. The new
    String.substring
    approach is better because it directly calls JS'
    substring
    , however it now produces:
    Copy code
    substring(response, startIndex, endIndex);
    Where
    substring
    is:
    Copy code
    function substring(_this__u8e3s4, startIndex, endIndex) {
      _init_properties_stringJs_kt__bg7zye();
      // Inline function 'kotlin.js.asDynamic' call
      return _this__u8e3s4.substring(startIndex, endIndex);
    }
    If instead you bring back
    inline
    for those two functions https://github.com/JetBrains/kotlin/blob/400e1ecadbef70744b6ee7eb6234a0a6ea8bbda8/libraries/stdlib/js/src/kotlin/text/stringJs.kt#L274-L276 you won't have to pass by the lazy initialization of the file-level properties. A similar situation is valid for
    Long
    too as far as I can see. Alternatively properties could be marked with
    EagerInitialization
    .
    a
    • 2
    • 5
  • m

    MrPowerGamerBR

    09/11/2025, 7:23 PM
    Is it possible to use
    @JsName
    on properties declared on a
    @JsPlainObject
    ? I wanted to change some
    snake_case
    variables into
    camelCase
    , to make it look "better" in Kotlin I tried searching for it, but the only result of someone trying to do this was this conversation: https://kotlinlang.slack.com/archives/C0B8L3U69/p1728428182216839 However after testing it, it doesn't seem to work on Kotlin 2.2.0 😞
    t
    • 2
    • 8
  • m

    Marc

    09/12/2025, 11:41 AM
    Are unsigned types fully supported on JS? I was trying to use them but I ran into a strange error:
    Copy code
    fun main() {
        ubyteArrayOf(
            *listOf(ubyteArrayOf())[0]
        )
    }
    results in:
    Copy code
    Unhandled JavaScript exception: listOf(...).get_c1px32_k$(...).slice is not a function
    https://pl.kotl.in/nEyBqjkBZ The same code works just fine when replacing
    ubyteArrayOf
    with
    byteArrayOf
    or running it on JVM instead.
    👀 1
    e
    • 2
    • 11
  • c

    CLOVIS

    09/13/2025, 4:01 PM
    Worried about bundle size? Here are two options that can help decrease it: • Using ESM modules • Using ES2015 language features Both of these articles give examples of how the options affect the generated code.
    ❤️ 8
    kodee loving 3