Creating and Running Koa.js Projects with ServBay
ServBay is a local web development environment for macOS and Windows, bundling essential developer tools such as Node.js runtime and multiple database servers. This guide walks you through rapidly creating, running, and managing your Koa.js project using ServBay’s integrated environment.
What is Koa.js?
Koa.js is an advanced web framework for Node.js developed by the team behind Express.js. Known for its lightweight, expressive, and powerful feature set, Koa.js is an ideal choice for building web applications and APIs. Koa leverages modern JavaScript capabilities, especially the async/await
syntax, allowing you to handle asynchronous tasks and middleware with greater clarity and maintainability.
Key Features of Koa.js
- Based on async/await: Designed around
async/await
, making asynchronous flow control intuitive. - Lightweight Core: The core library is minimal, providing only essential features—expanded via modular middleware.
- Powerful Middleware: Utilizes a cascading middleware architecture, making request handling clear and flexible.
- Web-Centric: Focused solely on web app and API development, without unnecessary added features.
Koa.js enables developers to efficiently build high-performance and maintainable web services.
Setting Up Koa.js Development Environment with ServBay
ServBay offers Node.js developers a ready-to-use local environment, integrating Node.js runtime and popular databases. With ServBay’s Website feature, you can conveniently access your local Koa.js projects using custom domains and SSL certificates.
Prerequisites
Before you start, please ensure:
- ServBay is Installed: Visit the ServBay official website to download and install the latest version.
- Node.js Package is Installed: Open the ServBay app, go to the Packages management section, and make sure your desired Node.js version is installed. If not, select and install it.
- Basic ServBay Usage: Know how to start/stop services and manage websites within ServBay.
Creating a Koa.js Project
We’ll use ServBay’s recommended website root directory /Applications/ServBay/www
to store your project files.
Initialize Project Directory
Open Terminal, navigate to ServBay’s website root, create a new folder (e.g.,
servbay-koa-app
), enter it, and initialize a Node.js project:bashcd /Applications/ServBay/www mkdir servbay-koa-app cd servbay-koa-app npm init -y
1
2
3
4The
npm init -y
command quickly generates a defaultpackage.json
file.Install Koa.js
Inside your project’s root directory
servbay-koa-app
, use npm to install Koa.js and its type definitions (if using TypeScript):bashnpm install koa # If you use TypeScript, install type definitions: # npm install @types/koa --save-dev
1
2
3Create Application Entry Point
Create a file named
app.js
in your project folder and add the following simple Koa.js app code:javascriptconst Koa = require('koa'); const app = new Koa(); // Middleware: Logs request details app.use(async (ctx, next) => { const start = Date.now(); await next(); const ms = Date.now() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); }); // Middleware: Handles requests to root path app.use(async ctx => { ctx.body = 'Hello from ServBay Koa.js App!'; }); // Define port, prioritize PORT environment variable const port = process.env.PORT || 3000; // Start HTTP server app.listen(port, () => { console.log(`Koa.js server running on http://localhost:${port}`); console.log(`Project path: ${__dirname}`); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24This code creates a basic Koa app with two middlewares: one that logs request time and path, and another that responds to
/
with "Hello from ServBay Koa.js App!". The app listens on the port specified by thePORT
environment variable or defaults to3000
.
Entering Development Mode
During development, you'll typically start a local Node.js process for your Koa.js app, accessed via ServBay’s Website feature.
Run the Koa.js Development Server
Open Terminal, move to the
servbay-koa-app
directory, and run the app usingnode
. To avoid port conflicts and make ServBay configuration easier, specify a dedicated port such as8585
:bashcd /Applications/ServBay/www/servbay-koa-app PORT=8585 node app.js
1
2The terminal should show
Koa.js server running on http://localhost:8585
, confirming the server is up and listening on port8585
. Keep this terminal window open for the server to continue running.Configure ServBay Website Reverse Proxy
To access your Koa.js app on
localhost:8585
via a custom domain, configure a Website in ServBay with a reverse proxy:- Open the ServBay app.
- Go to the Website section.
- Click the
+
button in the lower left to add a new website. - Fill in the configuration:
- Name:
ServBay Koa.js Dev Site
- Domain:
servbay-koa-dev.servbay.demo
(using.servbay.demo
helps ServBay auto-generate SSL certificates) - Type: Select
Reverse Proxy
- IP Address:
127.0.0.1
(points to your local Node.js process) - Port:
8585
(points to the Koa.js app port) - Document Root: Not important for reverse proxy; leave blank or enter
/Applications/ServBay/www/servbay-koa-app
.
- Name:
- Click save.
- Apply any changes when prompted.
After configuration, ServBay updates your local hosts file, mapping
servbay-koa-dev.servbay.demo
to127.0.0.1
. Requests to this domain are reverse-proxied to port8585
via Caddy or Nginx. Because you’re using a.servbay.demo
domain, ServBay User CA automatically issues and trusts the SSL certificate, letting you access your site securely via HTTPS.For more detailed steps, refer to ServBay documentation: Adding Node.js Development Website (be sure to select the English docs).
Access Your Koa.js Development Website
Open your browser and visit
https://servbay-koa-dev.servbay.demo
.If everything is set up correctly, you’ll see "Hello from ServBay Koa.js App!" displayed on the page. This means your local Koa.js development server is accessible via ServBay’s website feature. After editing
app.js
and restarting the server, you can simply refresh the browser to see the changes.
Deploying a Production Version (Simulation)
To simulate a production environment, you might use different ports, environment variables, or server start methods. ServBay’s reverse proxy setup works for this as well.
Run Koa.js Production Server (Simulated)
In another terminal window, stop the previously running development server (if necessary) and start the app in simulated production mode, e.g., on port
8586
and setNODE_ENV
:bashcd /Applications/ServBay/www/servbay-koa-app PORT=8586 NODE_ENV=production node app.js
1
2This launches a Koa.js instance listening on port
8586
, simulating a production environment.Configure ServBay Website Reverse Proxy (Production Simulation)
Similarly, create a new website in ServBay for the simulated production environment:
- Open the ServBay app and go to Website.
- Click the
+
button to add a new website. - Enter the configuration:
- Name:
ServBay Koa.js Prod Site
- Domain:
servbay-koa-prod.servbay.demo
(or use your own domain and get a free SSL cert via ServBay’s ACME/Let's Encrypt feature) - Type: Select
Reverse Proxy
- IP Address:
127.0.0.1
- Port:
8586
(points to the Koa.js production app) - Document Root: Leave blank or specify project path.
- Name:
- Save and apply changes.
Using a
.servbay.demo
domain continues to use ServBay User CA certificates. If you use your own public domain, ServBay supports automatic SSL/TLS certificates via ACME (Let’s Encrypt), letting you further simulate real-life production deployments. See documentation: Using SSL to Secure Website for details.Access the Simulated Production Website
Open your browser and go to
https://servbay-koa-prod.servbay.demo
.The page output should match your development environment, but this time requests are reverse-proxied to the Node.js process running on port
8586
.
Database Connections
ServBay bundles popular local database systems including MongoDB, Redis, MariaDB (MySQL compatible), and PostgreSQL. Connecting these databases to your Koa.js project is straightforward since they're locally hosted and accessible via localhost
with default settings.
Below are sample code snippets using Node.js drivers to connect to databases provided by ServBay. Make sure you’ve installed and started the relevant databases via ServBay’s Packages settings.
Connecting to MongoDB
First, install the MongoDB Node.js driver (like
mongoose
ormongodb
) in your project directory:bashcd /Applications/ServBay/www/servbay-koa-app npm install mongoose # or npm install mongodb
1
2Then, add connection code to
app.js
or another module:javascript// Use Mongoose to connect to MongoDB const mongoose = require('mongoose'); // ServBay MongoDB by default needs no authentication, database name is customizable mongoose.connect('mongodb://localhost:27017/servbay-koa-app', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('MongoDB connection error:', err)); // Note: In real apps, connection code is usually in the startup logic, // only starting to listen on the port after connection is successful.
1
2
3
4
5
6
7
8
9
10
11
12
13ServBay’s default MongoDB runs on port
27017
with no username or password. Database names can be specified directly (created automatically if missing).Connecting to Redis
Install the Redis Node.js client:
bashcd /Applications/ServBay/www/servbay-koa-app npm install redis
1
2Connect to the Redis server:
javascript// Use redis client to connect to Redis const redis = require('redis'); // Create Redis client, connects to localhost:6379 by default const client = redis.createClient({ url: 'redis://localhost:6379' // ServBay’s Redis default port }); client.on('connect', () => { console.log('Connected to Redis'); }); client.on('error', (err) => { console.error('Redis connection error:', err); }); // Connect to Redis server client.connect(); // Note: In practice, wait for successful connection before running Redis operations, // e.g., using async/await with client.connect()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21ServBay installs Redis on port
6379
, and default configuration does not require a password.Connecting to MariaDB (or MySQL)
MariaDB is a MySQL fork, highly compatible in API. ServBay offers MariaDB as a package, so treat it as MySQL in usage.
Install MariaDB’s Node.js driver:
bashcd /Applications/ServBay/www/servbay-koa-app npm install mariadb # or npm install mysql2 (better compatibility, recommended)
1
2To connect using
mariadb
:javascript// Use mariadb client to connect to MariaDB const mariadb = require('mariadb'); // ServBay’s MariaDB root password is 'password' by default const pool = mariadb.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'servbay_koa_app', // Ensure the database is created or change as needed connectionLimit: 5 }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB"); conn.release(); }) .catch(err => { console.error("MariaDB connection error:", err); }); // Note: Getting connections from the pool is asynchronous.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22Using
mysql2
(recommended):javascript// Use mysql2 client to connect to MariaDB/MySQL const mysql = require('mysql2/promise'); // ServBay’s MariaDB root password is 'password' by default const pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'servbay_koa_app', // Make sure the database exists waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB/MySQL using mysql2"); conn.release(); }) .catch(err => { console.error("MariaDB/MySQL connection error:", err); }); // Note: ServBay’s default root password can be viewed or modified in the ServBay GUI. // In real projects, avoid hardcoding passwords—use environment variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25MariaDB runs on port
3306
by default. The root password is available in the ServBay database management UI. You might need to manually create theservbay_koa_app
database using ServBay or a client tool (TablePlus, DBeaver, etc.).Connecting to PostgreSQL
Install the PostgreSQL Node.js driver:
bashcd /Applications/ServBay/www/servbay-koa-app npm install pg
1
2Connect to PostgreSQL server:
javascript// Use pg client to connect to PostgreSQL const { Pool } = require('pg'); // ServBay’s default PostgreSQL user 'user' with password 'password' const pool = new Pool({ user: 'user', // ServBay default user host: 'localhost', database: 'servbay_koa_app', // Ensure the database exists password: 'password', // ServBay default password port: 5432, // ServBay’s PostgreSQL default port }); pool.connect((err, client, done) => { if (err) { console.error('PostgreSQL connection error:', err); return; } console.log('Connected to PostgreSQL'); client.release(); }); // Note: ServBay’s default user/password can be viewed or changed in the GUI. // Avoid hardcoding passwords.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23PostgreSQL runs on port
5432
by default. Default username and password are available in the database management UI. You may need to manually create theservbay_koa_app
database.
Managing Databases in ServBay
Besides connecting via code, you can use GUI tools to manage the databases serviced by ServBay. These databases listen on 127.0.0.1
or localhost
; use ports and credentials shown in ServBay’s UI to connect.
- View/Change Default Password: In ServBay, locate the database package and click its settings icon to view or change the root (MariaDB) or user (PostgreSQL) passwords.
- Create Databases/Users: Use clients like TablePlus, DBeaver, pgAdmin, MongoDB Compass, etc., to connect to the databases and manage via SQL commands or GUI.
Notes
- Port Conflicts: Make sure your chosen Koa.js ports (i.e., 8585, 8586) aren’t used by other programs.
- ServBay Status: Ensure ServBay and required Node.js/database packages are running.
- Hosts File: ServBay manages your
hosts
file automatically—if domain resolution issues occur, check/etc/hosts
for matching records. - Firewall: Verify that macOS firewall or any third-party firewall isn’t blocking ServBay or Node.js network traffic.
- Log Inspection: For troubleshooting, review ServBay logs (in the app’s log tab) as well as terminal output from your Node.js processes.
Frequently Asked Questions (FAQ)
Q: Why use ServBay’s reverse proxy to access my Koa.js project?
A: Reverse proxying with ServBay’s website feature offers several benefits:
- Production-like environment simulation: Custom domains (
.servbay.demo
or your own) mimic real-world website access rather thanlocalhost:PORT
. - SSL support: ServBay auto-configures SSL certificates using User CA or Let’s Encrypt, so you can test HTTPS locally during development.
- Centralized management: All your local development sites can be managed together in ServBay—easy and convenient.
- Port abstraction: External visitors (if allowed) or browsers access sites via standard ports (80/443); internal requests are forwarded to higher port Node.js processes.
- Production-like environment simulation: Custom domains (
Q: Can I skip reverse proxy and access using
localhost:PORT
directly?A: Yes. If your Koa.js app is listening on a port (like 3000 or another), you can access it in your browser at
http://localhost:PORT
for development and testing. However, you won’t get ServBay’s custom domains, automatic SSL, or unified log management. For development that closely matches production deployments, ServBay’s reverse proxy is recommended.Q: What is ServBay’s default database password, and how do I change it?
A: ServBay’s default database passwords are shown within the app’s Database section. Click the settings icon next to your chosen database (MariaDB or PostgreSQL), and you’ll typically see the default user and password in the configuration window, where you can also change them. For security, you’re strongly advised to change default passwords.
Summary
This guide has shown you how to set up a complete Koa.js development environment on macOS using ServBay. You’ve created a basic Koa.js app, configured ServBay’s website feature with reverse proxy for custom domain and HTTPS access to your local app in both development and simulated production conditions, and learned how to connect to multiple popular databases provided by ServBay.
ServBay gives Node.js developers a powerful, integrated, and easy-to-manage local development setup, letting you focus more on coding and less on environment configuration. Harness the full power of ServBay for faster, more efficient development.