Creating and Running Koa.js Projects with ServBay
ServBay is a local web development environment designed specifically for macOS, integrating a variety of developer essentials such as the Node.js runtime and multiple databases. This guide will walk you through leveraging ServBay's powerful features to quickly create, run, and manage your Koa.js projects.
What is Koa.js?
Koa.js is a next-generation web framework for Node.js, developed by the creators of Express.js. Renowned for its simplicity, expressiveness, and robust feature set, Koa.js is an ideal choice for building web applications and APIs. It fully embraces modern JavaScript features, especially the async/await
syntax, dramatically simplifying asynchronous operations and middleware development, resulting in cleaner and more maintainable code.
Key Features of Koa.js
- async/await-based: The core is built around
async/await
, making asynchronous flow control more intuitive. - Lightweight core: The Koa core library is minimal, containing only essential features, while all other functionalities are extended via modular middleware.
- Powerful middleware: Implements cascading middleware, offering a clear and flexible request processing pipeline.
- Web-focused: Dedicated to web app and API development, omitting unnecessary extra features.
Using Koa.js enables developers to efficiently construct high-performance, maintainable web services.
Setting Up a Koa.js Development Environment with ServBay
ServBay offers Node.js developers a ready-to-use environment integrating Node.js runtimes and popular database services. With ServBay’s Website feature, you can seamlessly access your local Koa.js project via custom domains and SSL certificates.
Prerequisites
Before getting started, please ensure you’ve completed the following:
- Install ServBay: Download and install the latest version of ServBay from the official ServBay website.
- Install Node.js Package: Open the ServBay app, go to the Packages management panel, and ensure your required Node.js version is installed. If not, select and install it.
- Familiarize Yourself with ServBay Basics: Learn to start/stop services and manage websites in ServBay.
Creating a Koa.js Project
We'll use ServBay’s recommended root directory /Applications/ServBay/www
to store project files.
Initialize Project Directory
Open the Terminal app, navigate to ServBay’s web root directory, create a new project folder (e.g.,
servbay-koa-app
), enter it, and initialize a new 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 instantly generates a defaultpackage.json
file.Install Koa.js
In the
servbay-koa-app
project root, install Koa.js and its type definitions (if working with TypeScript):bashnpm install koa # If using TypeScript, install the type definitions # npm install @types/koa --save-dev
1
2
3Create the Application Entry File
In the project root directory
servbay-koa-app
, create a file namedapp.js
and add the following simple Koa.js app code:javascriptconst Koa = require('koa'); const app = new Koa(); // Middleware: Log request information 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: Handle root path requests app.use(async ctx => { ctx.body = 'Hello from ServBay Koa.js App!'; }); // Define the port, prefer environment variable PORT 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 sets up a basic Koa app with two middleware: one to log the request time and path, another to respond to root path
/
requests with "Hello from ServBay Koa.js App!". The app listens on the port specified by thePORT
environment variable or defaults to3000
.
Switch to Development Mode
During development, you'll typically run a local Node.js process hosting your Koa.js app, accessible via ServBay’s Website feature.
Run Koa.js Development Server
Open Terminal, navigate to the project directory
servbay-koa-app
, and runapp.js
with thenode
command. To avoid port conflicts and ease ServBay configuration, specify a port like8585
:bashcd /Applications/ServBay/www/servbay-koa-app PORT=8585 node app.js
1
2The terminal should output something like
Koa.js server running on http://localhost:8585
, indicating the server has started and is listening on port8585
. Keep this terminal window open to keep the server running.Configure ServBay Website Reverse Proxy
To access your Koa.js app running on
localhost:8585
via a custom domain, configure a Website in ServBay using reverse proxy:- Open the ServBay application.
- Go to the Website panel.
- Click the
+
button in the bottom left to add a new website. - Enter the site configuration:
- Name:
ServBay Koa.js Dev Site
- Domain:
servbay-koa-dev.servbay.demo
(a.servbay.demo
domain is recommended—ServBay will auto-generate an SSL certificate) - Type: Select
Reverse Proxy
- IP Address:
127.0.0.1
(points to the local Node.js process) - Port:
8585
(matches the Koa.js app’s listening port) - Document Root: For reverse proxy, this is not crucial; leave empty or set to
/Applications/ServBay/www/servbay-koa-app
.
- Name:
- Click Save.
- ServBay may prompt you to apply changes—click Apply when prompted.
After setup, ServBay automatically updates your local hosts file to point
servbay-koa-dev.servbay.demo
to127.0.0.1
, and routes requests to this domain through its built-in Caddy or Nginx server, proxying tolocalhost:8585
. With the.servbay.demo
domain, ServBay User CA auto-issues and trusts an SSL certificate so you can access your app securely via HTTPS.For detailed steps, check the ServBay documentation on adding Node.js development websites (make sure to select the English docs).
Access the Koa.js Development Website
Open your browser and visit
https://servbay-koa-dev.servbay.demo
.If everything is configured correctly, the page should display "Hello from ServBay Koa.js App!" This confirms you’re successfully reaching your local Koa.js development server via ServBay’s website feature. Any time you modify
app.js
and restart Node.js, simply refresh your browser to see the changes.
Deploying a Production Version (Simulation)
To simulate a production environment, you might need to use a different port, environment variables, or launch method. The ServBay reverse proxy setup works for this too.
Run Koa.js Production Server (Simulated)
In another terminal window, stop the development server if it’s still running, then start the app in a simulated production mode such as with port
8586
and theNODE_ENV
variable set:bashcd /Applications/ServBay/www/servbay-koa-app PORT=8586 NODE_ENV=production node app.js
1
2This starts a Koa.js instance on port
8586
, simulating a production environment.Configure ServBay Website Reverse Proxy (Production Simulation)
Similarly, set up a new website in ServBay for your simulated production environment:
- Open ServBay, navigate to the Website panel.
- Click the
+
button in the bottom left to add a new website. - Fill in:
- Name:
ServBay Koa.js Prod Site
- Domain:
servbay-koa-prod.servbay.demo
(or your own domain—for public domains, you can use ServBay’s ACME/Let’s Encrypt support to obtain free SSL certificates) - Type: Select
Reverse Proxy
- IP Address:
127.0.0.1
- Port:
8586
(points to your simulated production Koa.js instance) - Document Root: Leave empty or provide the project path.
- Name:
- Click Save and Apply changes.
Using a
.servbay.demo
domain continues to employ ServBay User CA certificates. If you use your own public domain, ServBay supports free SSL/TLS certificates via the ACME protocol (e.g. Let’s Encrypt), better simulating a real production environment. For more info, see the ServBay documentation on securing websites with SSL.Access the Koa.js Production Website (Simulated)
Open your browser and visit
https://servbay-koa-prod.servbay.demo
.You should see the same output as in development, except this time your request is handled by the Node.js process listening on port
8586
via ServBay’s reverse proxy.
Database Connections
ServBay integrates various popular databases including MongoDB, Redis, MariaDB (MySQL compatible), and PostgreSQL. Connecting to these databases from your Koa.js project is very convenient since they're all running locally and, by default, accessible via localhost
.
Here are sample code snippets to connect to several ServBay-provided databases using Node.js drivers. Make sure you’ve installed and started the relevant database packages in ServBay’s Packages panel.
Connect to MongoDB
First, install a MongoDB Node.js driver (such as
mongoose
ormongodb
) in your Koa.js project directory:bashcd /Applications/ServBay/www/servbay-koa-app npm install mongoose # or npm install mongodb
1
2Then, add the connection code in your
app.js
or other module:javascript// Connect to MongoDB using Mongoose const mongoose = require('mongoose'); // ServBay’s default MongoDB 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 usually goes in startup logic, // and the server only begins listening after the DB connection is successful.
1
2
3
4
5
6
7
8
9
10
11
12
13The default MongoDB installed by ServBay typically listens on port
27017
with no username or password required; specify your database name (it will be created automatically if it doesn't exist).Connect to Redis
Install a Redis Node.js client library:
bashcd /Applications/ServBay/www/servbay-koa-app npm install redis
1
2Connect to the Redis server:
javascript// Connect to Redis using the redis client const redis = require('redis'); // Create a Redis client; defaults to localhost:6379 const client = redis.createClient({ url: 'redis://localhost:6379' // ServBay default Redis port is 6379 }); 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 real apps, you may want to await client.connect() // before performing Redis operations (you can use async/await)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21The default Redis installed by ServBay listens on port
6379
and requires no password by default.Connect to MariaDB (or MySQL)
MariaDB is a drop-in replacement for MySQL—APIs are highly compatible. ServBay provides a MariaDB package, which you can use just like MySQL.
Install a MariaDB Node.js driver:
bashcd /Applications/ServBay/www/servbay-koa-app npm install mariadb # or npm install mysql2 (recommended for better compatibility)
1
2Using the
mariadb
driver:javascript// Connect to MariaDB using mariadb client const mariadb = require('mariadb'); // ServBay default MariaDB root password is 'password' const pool = mariadb.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'servbay_koa_app', // Ensure this DB exists or adjust as needed connectionLimit: 5 }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB"); conn.release(); // Release connection back to the pool }) .catch(err => { console.error("MariaDB connection error:", err); }); // Note: Fetching a connection is asynchronous in practice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22Using the
mysql2
driver (recommended):javascript// Connect to MariaDB/MySQL using mysql2 client const mysql = require('mysql2/promise'); // Use the Promise API // ServBay default MariaDB root password is 'password' const pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'servbay_koa_app', // Ensure the database exists waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB/MySQL using mysql2"); conn.release(); // Release connection back to pool }) .catch(err => { console.error("MariaDB/MySQL connection error:", err); }); // Note: The default root password can be viewed/changed in ServBay’s DB settings GUI. // It’s best practice to avoid hardcoding passwords in production.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25ServBay’s bundled MariaDB runs on port
3306
by default. The defaultroot
password can be found or changed in the ServBay database management dashboard. You may need to manually create theservbay_koa_app
database using ServBay or a database client such as TablePlus or DBeaver.Connect to PostgreSQL
Install the PostgreSQL Node.js driver:
bashcd /Applications/ServBay/www/servbay-koa-app npm install pg
1
2Connect to the PostgreSQL server:
javascript// Connect to PostgreSQL using pg client const { Pool } = require('pg'); // ServBay default PostgreSQL user 'user' password is 'password' const pool = new Pool({ user: 'user', // ServBay default user host: 'localhost', database: 'servbay_koa_app', // Ensure the DB exists password: 'password', // ServBay default password port: 5432, // ServBay default PostgreSQL port }); pool.connect((err, client, done) => { if (err) { console.error('PostgreSQL connection error:', err); return; } console.log('Connected to PostgreSQL'); client.release(); // Release connection back to the pool }); // Note: ServBay’s default user/passwords can be viewed/changed in the ServBay GUI. // Avoid hardcoding credentials in production.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23ServBay’s PostgreSQL package listens on port
5432
by default. You can find or change the user/password in the ServBay database dashboard. You may need to manually create theservbay_koa_app
database.
Managing Databases in ServBay
Besides connecting programmatically, you can use graphical tools to manage ServBay’s bundled databases. By default, the databases listen on 127.0.0.1
or localhost
, and you can use the credentials shown in ServBay’s GUI to connect.
- View/Change Default Passwords: In the ServBay app, find the relevant database package and open the settings icon to view or change the default
root
(MariaDB) oruser
(PostgreSQL) password. - Create Databases/Users: Use client tools like TablePlus, DBeaver, pgAdmin, or MongoDB Compass to connect to ServBay’s database service and create databases, users, tables, etc., via SQL or GUI.
Notes & Tips
- Port Conflicts: Make sure the ports you choose for your Koa.js app (e.g., 8585, 8586) are not occupied by other programs.
- ServBay Status: Ensure the ServBay app, required Node.js runtime, and database services are running.
- hosts File: ServBay manages your
hosts
file, but if you have DNS issues, check that an entry exists in/etc/hosts
. - Firewalls: Ensure that macOS or third-party firewalls are not blocking network connections for ServBay or Node.js.
- Logs: For troubleshooting, check ServBay’s logs (typically in the ServBay app’s Log panel) as well as Node.js terminal output.
Frequently Asked Questions (FAQ)
Q: Why use ServBay’s reverse proxy to access my Koa.js project?
A: Using a reverse proxy via ServBay’s Website feature has several benefits:
- Simulate Production: Accessing your app through a custom domain (like
.servbay.demo
or your own domain) rather thanlocalhost:PORT
better mimics real-world website access. - SSL Support: ServBay can auto-configure SSL certificates (via ServBay User CA or Let’s Encrypt) for your local sites so you can test HTTPS in development.
- Centralized Management: Manage all your local development sites within ServBay for convenience.
- Port Masking: External visitors (if allowed) or browsers connect via standard ports 80/443; traffic is internally proxied to higher ports where Node.js listens.
- Simulate Production: Accessing your app through a custom domain (like
Q: Can I skip the reverse proxy and just use
localhost:PORT
for development?A: Yes. If your Koa.js app listens on a port (e.g., 3000 or whichever you specify), you can directly visit
http://localhost:PORT
in your browser. However, you’ll miss out on ServBay’s custom domains, automatic SSL, logging, and other web-level conveniences. For development closely matching real deployment, using ServBay’s reverse proxy is recommended.Q: What are ServBay’s default database passwords, and how can I change them?
A: Default database passwords are shown in the Database tab within the ServBay app. Click the settings icon next to your desired database (e.g., MariaDB or PostgreSQL); the configuration window displays the current username and password. You can also change credentials in that window. For security, it’s recommended you update the default passwords.
Conclusion
This guide has shown you how to set up a Koa.js development environment on macOS using ServBay. We created a basic Koa.js app, configured reverse proxying in ServBay’s Website panel for access via custom domains and HTTPS, and learned how to connect to various built-in databases.
ServBay provides Node.js developers with an integrated and easily managed local development environment, allowing you to focus on coding instead of tedious environment setup. By leveraging ServBay’s powerful features, you can significantly boost your development productivity.