reactjsvite

How to run React Vite project correctly in production mode?


I'm using Vite with React, I want to run the project in production mode on a server. This is the vite.config.js :

export default defineConfig({
  esbuild: {
    loader: "jsx",
  },
  optimizeDeps: {
    esbuildOptions: {
      loader: {
        ".js": "jsx",
      },
    },
  },
  server: {
    port: 3000,
  }
});

And in the running pod on the server after deployment, I have this log :

Environment:
DEV_MODE=false
NODE_ENV=production
DEBUG_PORT=XXXX
Launching via npm...
> my-project start
> vite
npm http fetch GET 200 https://registry.npmjs.org/npm 2333ms (cache miss)
VITE v4.3 ready in 2303 ms
➜ Local: http://127.0.0.1:3000/
➜ Network: use --host to expose

Is it normal to have it running like that? Also on the port 3000? it looks like the log I get in my localhost.

If not, how can I run the project correctly in production mode and what's the right Vite config for it please?

And using react-react-app:

Environment:
DEV_MODE=false
NODE_ENV=production
DEBUG_PORT=XXXX
Launching via npm...
npm info it worked if it ends with ok
npm info using npm
npm info using node
> @my-app start /opt/app-root/src
> react-scripts start
ℹ 「wds」: Project is running at http://XX.XX.XXX.XXX/
ℹ 「wds」: webpack output is served from
ℹ 「wds」: Content not from webpack is served from /opt/app-root/src/public
ℹ 「wds」: 404s will fallback to /
Starting the development server...

Solution

  • This not the best way, to serve a React app using a dedicated server, but if you insist, you should use a solution with NGINX. First of all, from inspecting your logs, you run vite to start your application.

    Running just vite starts up a development server to serve your application, which is not good for production, https://vitejs.dev/guide/cli.html#dev-server.

    What you do need to do, is first to build your React application to get optimized static resources of your application ready to be served, using vite build, https://vitejs.dev/guide/cli.html#build.

    Then you need to use NGINX to serve your build artifacts.

    You can use this Dockerfile:

    FROM node:18-alpine3.17 as build
    
    WORKDIR /app
    COPY . /app
    
    RUN npm install
    RUN npm run build
    
    FROM ubuntu
    RUN apt-get update
    RUN apt-get install nginx -y
    COPY --from=build /app/dist /var/www/html/
    EXPOSE 80
    CMD ["nginx","-g","daemon off;"]
    

    then you need to run in your server:

    docker build -t vite-app .
    docker run -p 80:80 vite-app