App works locally (netlify dev) but don't work after published

Hello Everyone, I’m having a problem with my published App.

https://tourmaline-phoenix-71f436.netlify.app/

My App is working fine locally (netlify dev), and before publishing I had some problems with the build, but as you can see through the link it works now. The first problem occurs in the first page, the login section, where I use a netlify function to authenticate the user, all the inputs are provided but the login doesn’t work. Since the error is occuring when I’m retrieving the data (the log says “Cannot read properties of undefined (reading ‘data’)”, the problem is with my env variables? I use faunadb as database, and the connection and configuration are working fine in dev context. I printed the error but please let me know if more information is needed.

I’m using the env variables correctly? Is it really with the variables or other issue? Thanks for all the help, and I’m sorry if this topic was already covered.

Netlify Functions run on:

/.netlify/functions/function-name path. You’re using it on /login-user. Thus, a 404.

Thanks for the response! I see, but in my netlify.toml file I have configured the redirects section like this:

[[redirects]]
from = “/api/*”
to = “/.netlify/functions/:splat”
status = 200

Is that it?

If you do that, the path should be /api/login-user and not /login-user.

1 Like

Thanks @hrishikesh!

I just have a final question: my API endpoint since it was working locally was “http://localhost:8888/api/”, to work in production I had to update to the URL provided by the published version of the App by netlify, plus the “/api/”, which in my case is “https://tourmaline-phoenix-71f436.netlify.app/api/” (right?). Now I’m getting a CORS problem. I’ve already included headers in my login-user function with “Acess-Control-Allow-Origin”: “*”, and tried to include the headers params in netlify.toml but it didn’t work. So, in my code I have this:

The instance created to make axios calls:
image
The function that calls the netlify function:
image
netlify function (the return part):
image
error that I’m getting:

After the error above I get one with “Cannot read properties of undefined (reading data)”.

Sorry if this is a silly question. Again, thanks for all your help. I’ve tried a lot of things and I couldn’t make it work.

Why not simply use relative URLs like /api/login? What error were you getting with that setup?

Hi again @hrishikesh, thanks for the response. I was getting a preflight request error, but I managed to solve this issue after reading Access-Control-Allow-Origin Policy. I made an alteration in my function login-user as suggested in the post, and look like this now:

import { client, client_query as q } from '../src/config/db';
import * as jose from 'jose';
import bcrypt from "bcryptjs";

let HEADERS = {
  'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin',
  'Content-Type': 'application/json',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
  'Access-Control-Max-Age': '8640'
};

HEADERS['Access-Control-Allow-Origin'] = '*';
HEADERS['Vary'] = 'Origin';

export const handler = async (event, context) => {
  try {
    if (event.httpMethod === 'OPTIONS') {
      return { 
        HEADERS,
        statusCode: 200
      }
    }
    if(event.httpMethod = "POST") {
      const { email, password, type } = JSON.parse(event.body);

      const index = 
      type == "Profissional"
      ? "check_user_professional"
      : "check_user_client";

      const req = await client.query(
        q.Map(
          q.Paginate(q.Match(q.Index(index), email)),
          q.Lambda("user", q.Get(q.Var("user")))
      ));
      
      const authUser = { 
        id: req.data[0].ref.id,
        ...req.data[0].data
      }

      const validPassword = await bcrypt.compare(password, authUser.password);

      if(!validPassword){
        return {
          HEADERS,
          statusCode: 401,
          body: JSON.stringify("Login não Autorizado.")
        }
      }
      else{
        const secret = new TextEncoder().encode(process.env.JWT_SECRET);
        const token = await new jose
          .SignJWT({ id: authUser.id, type: authUser.userType })
          .setProtectedHeader({ alg: 'HS256' })
          .setIssuedAt()
          .setExpirationTime('7d')
          .sign(secret);

        return {
          HEADERS,
          statusCode: 200,
          body: JSON.stringify({
            authUser,
            token
          })
        }
      }
    }
  } catch (error) {
    return {
      HEADERS,
      statusCode: 400,
      body: JSON.stringify(error)
    }
  }
}

Just added the headers and changed to a post method. I made the change as you mentioned, using relative URL, like axios.post("api/login-user", ...), but I still get an error. This time, the request is failing with status code 400 and I’m getting a ERR_OUT_OF_RANGE in the data response. The error:


If there is anty other information I can provide, please, just let me know.

Hi @AgstAngelo ,

It looks like the 400 error is Axios related. I did some Googling and found this Stackoverflow thread with some possible solutions to resolve the error. Does this seem like this may help with the error that you’re seeing?

Hello @audrey , thanks for your help! I’m not sure if this is the problem, the function in my api file using axios was working already in my local, in netlify dev. Here it is by the way (if there’s something wrong with it please let me know):

export const loginUser = async (user) => {
  try {
    const response = await instance.post("login-user", // this was actually axios.post("api/login-user",...)
    { 
      email: user.email,
      password: user.password,
      type: user.userType 
    });

    return response;
    
  } catch (error) {
    return console.log(error);
  }
};

The response should be the user data and a token. I’m getting a 200 hundred response on preflight request but a 400 hundred after. Using relative URLs as mentioned by @hrishikesh didn’t work, with the baseURL setup at least the preflight request works. Am I missing something? I’m really stuck with this.

As I can see in your console output above, the error message is ERR_OUT_OF_RANGE and based on your code,

that part was sending it.

Somewhere in your code, a library could be throwing that error. This sounds out of scope for what we can debug.