eligolf
eligolf

Reputation: 1866

How do I host a Vue/Vite app with Express server on a hosting providor server?

I have a multiplayer game website similar to say chess.com or lichess but for another game. I use Vite with Vue for front end and express for backend, comminucation with socket.io and database in mongodb.

It all works fine on localhost so now I want to try and upload to my hosting providor. I have a virtual private server (VPS) which uses Direct Admin which has access to my folder structure under mywebsite.com folder.

I have a .env file which holds the variable VITE_SERVER_URI=http://localhost:5000 and then I have a .env.production file which similarily holds VITE_SERVER_URI=https://mywebsite.com.

The project structure is I have a root which in turn holds .env, .env.production, src etc. Then src holds my vue components and also the server folder which holds the server.js file which looks like this:

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import authRoutes from './routes/auth.js';
import http from 'http';
import { Server } from 'socket.io';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Set up dotenv
dotenv.config({ path: path.join(__dirname, '../../.env') });

// Cors
const allowedOrigins = [
    'http://localhost:5000',
    'http://localhost:5173',
    'https://mywebsite.com',
  ];

// Create app
const app = express();
app.use(express.json());
app.use(cors({ 
    origin: allowedOrigins,
    credentials: true,
}));

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI)
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.error('MongoDB connection error:', err));

// Create HTTP server and socket.io instance
const server = http.createServer(app);
const io = new Server(server, {
    cors: {
        origin: allowedOrigins,
        methods: ["GET", "POST", "DELETE"],
        credentials: true
    }
});

// Set up the routes
app.use('/api', authRoutes);

// Start the server
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

What works

What doesn't work

What I tried

Questions

Please let me know if you need more code or information.

Upvotes: 0

Views: 186

Answers (0)

Related Questions