sveltekitnetlify-function

Why is Sveltekit (1.0) showing "Cant find module jsonwebtoken"?


I have a sveltekit app running locally fine. When deployed to Netlify it is giving me an error 'Cannot find module 'jsonwebtoken' .. ?

I installed jsonwebtoken in the app folder (not globally). It is in my package.json.

The error is triggered within a Netlify serverless function which has at the top of the file ..

const jwt = require('jsonwebtoken')

Im suspecting dotenv / environment variables as i have had other issues related to these and I am using them here is this netlify login function. Any ideas/ suggestions welcome.

Update: I commented out the code requiring and using jsonwebtoken and the rest of the function worked fine, so there is an issue with Sveltekit 1.0 and jsonwebtoken and even though this is within a netlify function, I dont think its a netlify issue. Anyone know of alternative to jsonwebtoken?.


Solution

  • Solution: replace

    const jwt = require('jsonwebtoken')
    

    with

    import * as jwt from 'jsonwebtoken';
    

    It appears that Sveltekit, when deployed to Netlify so could be sveltekit adapter, doesnt like "require".

    Hours of changing netlify.toml, trying adapter-auto, then searching for alternatives and then it occurred to me to try import instead of require and just like that, it worked. The "require" worked locally but not when deployed, at least not for me. Having switched back and forth many times now, the require fails every time and the import works every time.

    In case anyone else is fighting this issue, here is my netlify.toml file and svelte.config.js file. My netlify functions are in the standard netlify/functions folder so dont need to specify in netlify.toml.

    netlify.toml

    [build]
    command="vite build"
    publish = "build"
    

    svelte.config.js

    import adapter from '@sveltejs/adapter-netlify';
    /** @type {import('@sveltejs/kit').Config} */
    const config = {
        kit: {
            adapter: adapter()
        }
    };
    
    export default config;
    

    PS. the dotenv issue I mentioned may have been a "require" issue also. Have to check.