Netlify functiob getUserData.mjs not working / (giving big errors) /

hey, im getting some issues with my netlify functions. i’ve got a my own getUserData function for my login page, but i got some errors with it…

import fs from ‘fs’;

export default async (event, context) => {
const queryParams = event.queryStringParameters;

// if (!queryParams || !queryParams.number) {
// return new Response(JSON.stringify({ message: ‘Number parameter is required’ }), {
// status: 400,
// headers: {
// ‘Content-Type’: ‘application/json’
// }
// });
// }

// const { number } = queryParams;
const number  = queryParams.number;
// Construct the file path based on the number parameter
const filePath = `/.netlify/functions/getUserData_${number}.json`;

try {
    // Check if the file exists
    fs.accessSync(filePath, fs.constants.F_OK);

    // File exists, read its contents
    const userData = fs.readFileSync(filePath, 'utf8');
    return new Response(userData, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
} catch (error) {
    // File doesn't exist
    return new Response(JSON.stringify({ message: 'User not found' }), {
        status: 404,
        headers: {
            'Content-Type': 'application/json'
        }
    });
}

};

getUserData.mjs code ^^^

{“number”:“sleepy”,“ssn”:“050102-1377”,“name”:“Sleepy 1.8”,“expiry”:“2025-04-22”,“imageUrl”:“/assets/proFENI.png”}

getUserData_dak.json code ^^

login.js code

document.getElementById(“login-button”).addEventListener(“click”, function () {
const a = document.getElementById(“user-number-input”).value;
fetch(“/.netlify/functions/getUserData?number=” + a).then(a => a.json()).then(a => {
if (a && !a.msg) {
localStorage.setItem(“userData”, JSON.stringify(a));
window.location.href = “index.html”;
} else {
alert(“Fel kod!”);
}
}).catch(a => {
console.error(“Error:”, a);
alert(“An error occurred while trying to fetch user data.”);
});
});
document.addEventListener(“DOMContentLoaded”, function () {
document.getElementById(“no-button”).addEventListener(“click”, function () {
window.location.href = “https://discord.gg/”;
});
});

website https://663f5c659af016e412a06ff2--bk-idn.netlify.app/

error / issue

This function has crashed

An unhandled error in the function code triggered the following message:

TypeError - Cannot read properties of undefined (reading ‘number’)

Stack trace

TypeError: Cannot read properties of undefined (reading 'number')
    at Module.getUserData_default (file:///var/task/getUserData.mjs:14:30)
    at Runtime.handler (file:///var/task/___netlify-bootstrap.mjs:3734:33)
    at Runtime.handleOnceStreaming (file:///var/runtime/index.mjs:1199:38)
in https://663f5c659af016e412a06ff2--bk-idn.netlify.app/.netlify/functions/getUserData?number=dak

Connection details

and before when i didnt have all those “//” i got the issue

{“message”: “Number parameter is required” }

in /.netlify/functions/getUserData?number=dak

can anyone help me i beg you

You’re using Functions V2 (the currently supported version) and that does not use event anymore as the first parameter, but rather request . You should rename the function argument, and you can see here in MDN what methods and properties the object will have: Request - Web APIs | MDN

To read a query parameter named number: new URL(request.url).searchParams.get('number')

hello! thannks! it managed to fix it.

But it won’t load the .json files i have
for example “getUserData_dak.json” exists in /.netlify/functions but when i type the code “dak”

it console logs this

login.js:13 GET https://6640939…–bk-idn.netlify.app/.netlify/functions/getUserData?number=dak 404 (Not Found)

fetchUserData @ login.js:13
(anonymous) @ login.js:3

login.js:15

  1. Response {type: ‘basic’, url: ‘https://6640939e329d2ab2b3ce19bd--bk-idn.netlify.app/.netlify/functions/getUserData?number=dak’, redirected: false, status: 404, ok: false, …}

login.js:19

  1. {message: ‘User not found’}

  2. message: “User not found”

  3. [[Prototype]]: Object

login.js:13 Fetch failed loading: GET “https://6640939…–bk-idn.netlify.app/.netlify/functions/getUserData?number=dak”.

fetchUserData @ login.js:13
(anonymous) @ login.js:3

and wont work… : (

Your post is very difficult to read due to lack of formatting. Please format it better so others can better understand what you’re saying. As for the missing files, check if this relates to your case: How to Include Files in Netlify Serverless Functions

when the url is

https://6640aea582f5fec08f049dd4--bk-idn.netlify.app/.netlify/functions/getUserData?number=dak

it responds with {“message”:“User not found”}

when the url is

https://6640aea582f5fec08f049dd4--bk-idn.netlify.app/.netlify/functions/getUserData_dak

it responds with {“number”:“sleepy”,“ssn”:“050102-1377”,“name”:“Sleepy 1.8”,“expiry”:“2025-04-22”,“imageUrl”:“/assets/proFENI.png”}

it is supposed to read what it responds on second url. it has to be ?number=dak tho.

the getUserData_dak.mjs code is

`export default async (req, context) => {
    return new Response(JSON.stringify({"number":"sleepy","ssn":"050102-1377","name":"Sleepy 1.8","expiry":"2025-04-22","imageUrl":"/assets/proFENI.png"}));
};`

and the getUserData.mjs code is

import fs from 'fs';

export default async (request, context) => {
    // Extract the 'number' parameter from the query string
    const queryParams = new URLSearchParams(request.url.split('?')[1]);
    const number = queryParams.get('number');

    // Construct the file path based on the 'number' parameter
    const filePath = `/.netlify/functions/getUserData_${number}.mjs`;

    try {
        // Check if the file exists
        fs.accessSync(filePath, fs.constants.F_OK);

        // File exists, import the module
        const userData = await import(filePath);
        
        // Return the user data
        return new Response(JSON.stringify(userData.default), {
            headers: {
                'Content-Type': 'application/json'
            }
        });
    } catch (error) {
        // File doesn't exist or error occurred
        return new Response(JSON.stringify({ message: 'User not found' }), {
            status: 404,
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }
};

since i managed to fix the error. and i changed myself from .json to .mjs to see if it would atleast reas it out and yes it did but not in the url i want it to.

This explanation helps, thanks!

This is expected not to work. The guide I linked above talks exactly about that.