Skip to main content

Overview

Mokepon is designed to be deployed on Heroku, a cloud platform that supports Node.js applications. The deployment process is straightforward and leverages Heroku’s automatic deployment from Git.

Heroku Deployment

Prerequisites

Before deploying, ensure you have:
  • A Heroku account (sign up here)
  • Heroku CLI installed (installation guide)
  • Git installed and repository initialized
  • All changes committed to your Git repository

Deployment Process

1

Login to Heroku

Authenticate with Heroku via the CLI:
heroku login
This will open a browser window for authentication.
2

Create a Heroku app

Create a new Heroku application:
heroku create mokepon-game
Or let Heroku generate a random name:
heroku create
The live Mokepon game uses the URL: https://mokepon-ed1d40aff3a6.herokuapp.com/
3

Configure environment variables

Set the production environment variable:
heroku config:set NODE_ENV=production
The PORT variable is automatically set by Heroku and doesn’t need manual configuration.
4

Deploy to Heroku

Push your code to Heroku:
git push heroku main
Or if your default branch is master:
git push heroku master
Heroku will automatically:
  • Detect the Node.js application
  • Install dependencies from package.json
  • Run the start script defined in the Procfile
5

Open your application

Once deployment is complete, open your app:
heroku open
Or visit the URL provided during app creation.

Procfile Configuration

The Procfile tells Heroku how to run your application:
Procfile
web: node index.js
This simple configuration:
  • Defines a web process type (required for web applications)
  • Executes node index.js to start the Express server
  • Automatically binds to Heroku’s dynamically assigned PORT
Heroku uses the Procfile to determine which command to run. The web process type is special because it’s the only process that receives HTTP traffic.

Environment Variables

Required Variables

VariableSet ByDescription
PORTHerokuAutomatically assigned port (DO NOT override)
NODE_ENVYouSet to "production" for production behavior

Setting Environment Variables

Using Heroku CLI:
# Set a variable
heroku config:set NODE_ENV=production

# View all variables
heroku config

# Get a specific variable
heroku config:get NODE_ENV

# Remove a variable
heroku config:unset VARIABLE_NAME
Using Heroku Dashboard:
  1. Navigate to your app in the Heroku dashboard
  2. Go to Settings tab
  3. Click Reveal Config Vars
  4. Add or edit variables

PORT Environment Variable

The server dynamically uses Heroku’s PORT:
index.js
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
Never hardcode the port in production. Always use process.env.PORT to ensure Heroku can bind the application correctly.

Production Configuration

Environment Detection

The application behaves differently in production:
index.js
// Only load dotenv in development
if (process.env.NODE_ENV !== "production") {
  const dotenv = await import("dotenv");
  dotenv.config();
}
This ensures .env files are only used during local development, not in production where environment variables come from Heroku’s config.

CORS Configuration

CORS is restricted in production for security:
index.js
const corsOptions = {
  origin:
    process.env.NODE_ENV === "production"
      ? "https://mokepon-ed1d40aff3a6.herokuapp.com"
      : "*",
  methods: ["GET", "POST", "DELETE"],
  allowedHeaders: ["Content-Type", "Authorization"],
};

app.use(cors(corsOptions));
In production, update the CORS origin to match your Heroku app’s URL. Replace mokepon-ed1d40aff3a6.herokuapp.com with your actual domain.

Security Middleware

The application uses Helmet to set secure HTTP headers:
index.js
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "https://cdn.jsdelivr.net"],
        connectSrc: ["'self'"],
        imgSrc: ["'self'", "data:"],
        styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
        fontSrc: ["'self'", "https://fonts.gstatic.com"],
        workerSrc: ["'self'", "blob:"],
        childSrc: ["'self'", "blob:"],
      },
    },
  })
);
This Content Security Policy (CSP) configuration:
  • Restricts resource loading to same origin by default
  • Allows external scripts from CDN (jsdelivr)
  • Permits Google Fonts for styling
  • Prevents XSS attacks and unauthorized resource loading

Response Compression

Compression middleware reduces payload size:
index.js
import compression from "compression";
app.use(compression());
This automatically compresses HTTP responses, improving load times especially for users on slower connections.

Error Handling

Production Error Responses

Error handling differs between development and production:
index.js
app.use((err, req, res, next) => {
  const status = err.status || 500;
  const message = err.message || "Internal Server Error";

  console.error(`Error ${status}: ${message}`);

  res.status(status).json({
    success: false,
    message,
    error: process.env.NODE_ENV === "production" ? undefined : err.stack,
  });
});
In production:
  • Stack traces are hidden from API responses
  • Only the error message is sent to clients
  • Full errors are logged server-side for debugging
In development:
  • Full stack traces are included in responses
  • Makes debugging easier during development

Node.js Version

The application specifies the Node.js version in package.json:
package.json
{
  "engines": {
    "node": ">=14.0.0"
  }
}
Heroku will use this to select the appropriate Node.js runtime. The >=14.0.0 requirement ensures ES module support.

Deployment Checklist

Before deploying to production, verify:
1

Code quality

  • All features tested locally
  • No console errors in browser
  • All API endpoints functioning correctly
  • Game mechanics working as expected
2

Configuration

  • package.json has correct dependencies
  • Procfile points to correct entry file
  • Environment variables configured
  • CORS origin updated to production URL
3

Security

  • No sensitive data in repository
  • .gitignore includes .env
  • Helmet CSP properly configured
  • CORS restricted in production
4

Performance

  • Compression enabled
  • Static assets optimized
  • Images compressed
  • No unnecessary dependencies

Monitoring and Logs

Viewing Logs

View real-time logs from your Heroku app:
# Stream logs
heroku logs --tail

# View recent logs
heroku logs --num 100

# Filter by process type
heroku logs --ps web

Application Metrics

Monitor your application through the Heroku dashboard:
  1. Navigate to your app
  2. Click on the Metrics tab
  3. View response times, throughput, memory usage, etc.

Troubleshooting

Application Crashes

If your app crashes:
# Check logs
heroku logs --tail

# Restart the app
heroku restart

# Check dyno status
heroku ps

Port Binding Issues

Ensure your application uses process.env.PORT:
// ✅ Correct
const port = process.env.PORT || 3000;

// ❌ Wrong - hardcoded port won't work on Heroku
const port = 3000;

Build Failures

If the build fails:
  1. Check that all dependencies are in package.json
  2. Ensure Node.js version compatibility
  3. Verify the Procfile is correct
  4. Review build logs for specific errors

CORS Errors

If you see CORS errors in production:
  1. Verify the CORS origin matches your Heroku URL
  2. Check that NODE_ENV is set to "production"
  3. Ensure allowed methods include those your client uses

Continuous Deployment

For automatic deployments from GitHub:
1

Connect GitHub

In the Heroku dashboard:
  1. Go to your app’s Deploy tab
  2. Select GitHub as deployment method
  3. Connect your GitHub account and repository
2

Enable automatic deploys

  1. Choose the branch to deploy (usually main or master)
  2. Click Enable Automatic Deploys
  3. Optionally enable Wait for CI to pass before deploy
Now every push to your selected branch will automatically deploy to Heroku.

Custom Domain (Optional)

To use a custom domain:
# Add a domain
heroku domains:add www.yourdomain.com

# View domains
heroku domains
Then configure your DNS provider to point to Heroku.

Next Steps

  • Review project structure to understand the codebase
  • Check setup guide for local development
  • Monitor your application logs and metrics regularly
  • Consider implementing additional features or optimizations

Build docs developers (and LLMs) love