Unexpected end of JSON input (react vite app)

netlify site name: csu-climb.netlify.app

Hello,

So I made a react vite app following almost exactly the same architecture as this code from a tutorial, from making two seperate react apps for frontend and backend running on ports 3000 and 5000 respectively, to doing the same redirection in server.js so that both app would run under one port for deployment. In the tutorial he hosts the website on render while I decided to host in netlify. Problem is after deploying my website and trying to login, I get the error "Unexpected token ‘<’, "<!DOCTYPE “… is not valid JSON”. From what I understood, the app is getting html instead of json form the backend?

Here is how I configured my app before building and dropping the dist for deployment:

frontend/vite.config.js:

import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    proxy: {
      "/api": {
        target: "http://localhost:5000",
        changeOrigin: true,
      },
    },
  },
});

while my endpoints all use fetch like this const res = await fetch("/api/auth/me");

scripts in package.json:

  "scripts": {
    "dev": "cross-env NODE_ENV=development nodemon backend/server.js",
    "start": "cross-env NODE_ENV=production node backend/server.js",
    "build": "npm install && npm install --prefix frontend && npm run build --prefix frontend"
  },

backend/server.js:

import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import {v2 as cloudinary} from "cloudinary";

import authRoutes from "./routes/auth.route.js";
import userRoutes from "./routes/user.route.js";
import routeRoutes from "./routes/route.route.js";
import notificationRoutes from "./routes/notification.route.js";
import leaderboardRoutes from "./routes/leaderboard.route.js";

import connectMongoDB from "./db/connectMongoDB.js";

import path from "path";

dotenv.config();

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
});

const app = express();
const PORT = process.env.PORT || 5000;
const __dirname = path.resolve();

app.use(express.json( {limit:"5mb"} ));
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.use(cookieParser()); //middleware to parse cookies

app.use("/api/auth", authRoutes);
app.use("/api/users", userRoutes);
app.use("/api/routes", routeRoutes);
app.use("/api/leaderboard", leaderboardRoutes);
app.use("/api/notifications", notificationRoutes);

if(process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, "/frontend/dist")));

    app.get("*", (req, res) => {
        res.sendFile(path.resolve(__dirname, "frontend", "dist", "index.html"));
    });
}

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
    connectMongoDB();
})

I already have the _redirects file in the /public folder. please help!

Thank you in advance

@Hemzyy I’ve not looked at the specifics, but since the tutorial you followed was for ‘render’ and you decided to host on ‘Netlify’ you may not be able to use it “as is”, it’s possible you’ll need to adjust.

See the following links for more details:
Can I run a web server, HTTP listener, and/or database at Netlify?
Express on Netlify

@nathanmartin Ah yes, thank you for pointing that out. I went ahead and followed the vite on netlify page and instead of just dropping the dist folder for deployment, I am now depoying directly from github. But the issue still presists as I get the error Unexpected token '<', "<!DOCTYPE "... is not valid JSON when there is a fetch request from the backup.

So for now, xcept for the netlify setup and the netlify.toml file:

# example netlify.toml
[build]
  base = "frontend"
  command = "npm install && npm run build"
  functions = "netlify/functions"
  publish = "dist"

  ## Uncomment to use this redirect for Single Page Applications like create-react-app.
  ## Not needed for static site generators.
  #[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

  ## (optional) Settings for Netlify Dev
  ## https://github.com/netlify/cli/blob/main/docs/netlify-dev.md#project-detection
  #[dev]
  #  command = "yarn start" # Command to start your dev server
  #  port = 3000 # Port that the dev server will be listening on
  #  publish = "dist" # Folder with the static content for _redirect file

  ## more info on configuring this file: https://ntl.fyi/file-based-build-config

The rest of the code is still the same as the one I posted in the beginning

@Hemzyy It seems you may have misunderstood the crux of my response.

I wasn’t referring to your frontend or how it’s deployed, but rather your backend.

It’s likely it’s not even running due to how it is currently constructed.

What you’re seeing is your app receiving the standard Netlify 404 page upon calling the backend.

Ah I apologize for not seeing this earlier, from what I understood, I will need to run my backend server on another service or third party app and redirect my website’s request to it?

@Hemzyy If you want to use the code unchanged, then yes.

You can also investigate adjusting so that it works with Serverless Functions, which is why I linked to:
Express on Netlify