node.js deployment crash
debuck1718
HOBBYOP

7 months ago

after setting my project, anytime i try building it up it results in crash without any log detail error which can point to one or two. Just "smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js". I have changed my server.js file many times and install the omit=dev but still get same error. I'm using railway database too linked to my project. I'm so confused about and would be happy if you could help with it. Lemme know if you would want me to share the server.js code with you to pinpoint any mistake from my end. Thank you and hoping to hear from you soon.

$10 Bounty

7 Replies

Railway
BOT

7 months ago


Railway

Hey there! We've found the following might help you get unblocked faster: - [🧵 Environment keeps crashing after node update](https://station.railway.com/questions/environment-keeps-crashing-after-node-up-713796fd) - [🧵 Can you help with this problem, locally I don't have leak of memory and heap size increased to 4096 ](https://station.railway.com/questions/can-you-help-with-this-problem-locally-5a7d66d7) - [🧵 Build keeps crashing (Fastify 5 + Prisma Build Failures)](https://station.railway.com/questions/build-keeps-crashing-fastify-5-prisma-4cbee66c) - [🧵 Deploy Successful, Then SIGTERM and app stops.](https://station.railway.com/questions/deploy-successful-then-sigterm-and-app-2b6a7c53) If you find the answer from one of these, please let us know by solving the thread!

debuck1718
HOBBYOP

7 months ago

this does not answer my question


essaubaid
FREE

7 months ago

Did you check if you have the ports setup correctly? There must be separate build logs as well, what do they say?


essaubaid

Did you check if you have the ports setup correctly? There must be separate build logs as well, what do they say?

debuck1718
HOBBYOP

7 months ago

I have set the environment variable for my project along with the ones provided by the platform. The logs that I see is "

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

npm warn config production Use --omit=dev instead.

> smartstudent@1.1.0 start

> node server.js

"

It builds completely and deploys successfully for 36 seconds then result in crash with the above logs in the log section and deploy logs.


smolpaw
HOBBY

7 months ago

The reason you have multiple of the same error is that it's restarting over and over again. You can also ignore the --omit=dev warning
Do post your server.js file


smolpaw

The reason you have multiple of the same error is that it's restarting over and over again. You can also ignore the --omit=dev warningDo post your server.js file

debuck1718
HOBBYOP

7 months ago

here's a copy of my server.js file "

/**
 * server.js
 * SmartStudent Backend API Main Server
 * This file is the entry point for the SmartStudent Express application.
 * It sets up the server, database connection, middleware, and
 * schedules background tasks.
 */
const express = require('express');
const http = require('http'); // Required for session store setup
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const dotenv = require('dotenv');
const { EventEmitter } = require('events'); // Event bus for inter-module communication
const cron = require('node-cron'); // Cron job for scheduled tasks
const { DateTime } = require('luxon'); // Luxon for date and time handling

// --- Database & Session Store Dependencies ---
const pgp = require('pg-promise')();
const session = require('express-session');
const pgSession = require('connect-pg-simple')(session);

// --- Local Dependencies ---
const logger = require('./utils/logger'); // Winston logger
const buildRouter = require('./routes'); // Your route definitions

// --- Load Environment Variables ---
dotenv.config();

// --- Main Application Setup ---
const app = express();
const eventBus = new EventEmitter(); // Event bus for system-wide events

// --- Database Connection ---
const dbConfig = {
    connectionString: process.env.DATABASE_URL,
    ssl: { rejectUnauthorized: false }
};

if (!dbConfig.connectionString) {
    logger.error('❌ DATABASE_URL environment variable is not set. Exiting.');
    process.exit(1);
}

const pool = new pgp.Pool(dbConfig);
const db = pgp(dbConfig);

// Test database connection on startup
db.connect()
    .then(obj => {
        obj.done(); // success, release connection
        logger.info('✅ PostgreSQL connected successfully.');
    })
    .catch(error => {
        logger.error('❌ Database connection error:', error.message);
        process.exit(1); // Exit if DB connection fails
    });

// --- Middleware Setup ---
app.use(cors({
    origin: process.env.FRONTEND_URL || '*', // Use env var for production
    credentials: true
}));
app.use(helmet()); // Secure Express apps by setting various HTTP headers
app.use(morgan('tiny', { stream: { write: message => logger.info(message.trim()) } })); // Logging with Winston
app.use(express.json()); // Body parser for JSON
app.use(express.urlencoded({ extended: false })); // Body parser for URL-encoded data


// --- Session Configuration ---
if (!process.env.SESSION_SECRET) {
    logger.error('❌ SESSION_SECRET environment variable is not set. Exiting.');
    process.exit(1);
}

const sessionStore = new pgSession({
    pool: pool, // Use the pg-promise pool
    tableName: 'user_sessions'
});

app.use(session({
    store: sessionStore,
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24 * 7 // 7 days
    }
}));

cron.schedule('*/5 * * * *', () => { // Runs every 5 minutes
    logger.info('⏰ Running scheduled reminder check...');
    const now = DateTime.now().toJSDate();
    // In a real application, you would query the database here for tasks/reminders
    // that are due soon and send out notifications using webpush or Twilio.
    logger.info(`Checking for upcoming reminders at ${now}`);
});


// --- Mount the API Router ---
// Pass the database pool and event bus to the router
app.use('/', buildRouter(db, eventBus));


// --- Error Handling for API Calls ---
app.use((req, res) => {
    res.status(404).json({ error: 'Not Found', message: `The requested path '${req.path}' does not exist.` });
});

app.use((err, req, res, next) => {
    logger.error('Unhandled Error:', err.stack);
    res.status(500).json({ error: 'Internal Server Error', message: 'An unexpected error occurred.' });
});


// --- Unhandled Rejection and Uncaught Exception Handlers ---
// These ensure the process doesn't crash on unhandled async errors
process.on('unhandledRejection', (reason, promise) => {
    logger.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
    // Application might be in an unstable state, so exit gracefully
    server.close(() => process.exit(1));
});

process.on('uncaughtException', err => {
    logger.error('❌ Uncaught Exception:', err.stack);
    // Application might be in an unstable state, so exit gracefully
    server.close(() => process.exit(1));
});


// --- Start the Server ---
const PORT = process.env.PORT || 4000;
const server = http.createServer(app);

server.listen(PORT, () => {
    logger.info(`✅ Server is running on port ${PORT} in ${process.env.NODE_ENV || 'development'} mode.`);

"


nizo-developer
FREE

7 months ago

The issue is with this line:

const pool = new pgp.Pool(dbConfig);

pg-promise doesn’t expose Pool. That’s from the pg library, not pg-promise.

const db = pgp(dbConfig); const pool = db.$pool;

This gives you access to the connection pool properly. It's the correct and up-to-date way with pg-promise.


Loading...