Creating and Running an Express.js Project with ServBay
What is Express.js?
Express.js is a fast, open-source, and minimalist web application framework built on Node.js. It delivers a wide array of powerful features for building single-page, multi-page, and hybrid web applications. As one of the most popular frameworks in the Node.js ecosystem, Express.js is beloved by developers for its simplicity and flexibility.
Core Features and Advantages of Express.js
- Simple & Flexible: Express.js provides a clean API and a flexible middleware system, making web application development highly efficient.
- Middleware Support: It supports diverse middleware, enabling easy handling of requests and responses, such as parsing request bodies, managing sessions, and serving static files.
- Robust Routing: Powerful routing capabilities allow handling requests according to different HTTP methods (GET, POST, PUT, DELETE, etc.) and URL paths.
- Seamless Integration: Effortlessly integrates with various template engines (like Pug, EJS, Handlebars), databases (such as MongoDB, MySQL, PostgreSQL), and other Node.js modules.
- Community and Ecosystem: Backed by a large community and extensive third-party middleware and plugin support, making it easy to find solutions and resources when issues arise.
Using Express.js, developers can quickly build high-performance web applications and APIs. As a robust local web development environment, ServBay provides a convenient Node.js environment, powerful website (reverse proxy) management, and database management features for running Express.js projects efficiently.
Creating and Running an Express.js Project with ServBay
This tutorial will guide you through creating, configuring, and running an Express.js project using the Node.js environment provided by ServBay. We will utilize ServBay's Websites feature to set up the web server and access your project via reverse proxy. This is especially suited for applications that need to run on custom ports, such as those built with Node.js, Python, Go, or Java.
Prerequisites
Before you start, please make sure you meet the following requirements:
- ServBay is successfully installed on your macOS system.
- The Node.js package is installed and enabled in ServBay. You can manage this from the “Packages” tab in the ServBay Control Panel.
- (Optional) If you plan to connect to a database, make sure the corresponding database package (such as MariaDB, PostgreSQL, MongoDB, Redis, MySQL) is installed and enabled in ServBay.
- Basic familiarity with terminal or command-line operations.
Creating an Express.js Project
Initialize the Project
First, open your terminal and navigate to ServBay's recommended web root directory at
/Applications/ServBay/www
. Use thenpx express-generator
command to quickly scaffold an Express.js project.npx
is included with npm v5.2+ for executing Node.js package binaries.bashcd /Applications/ServBay/www npx express-generator servbay-express-app
1
2This will create a new folder named
servbay-express-app
under/Applications/ServBay/www
containing a basic Express.js project structure.Install Project Dependencies
Change into the newly created project directory
servbay-express-app
and usenpm install
to fetch all necessary dependencies, including Express.js and default packages for functions like template engines and static file serving.bashcd servbay-express-app npm install
1
2Wait for all dependencies to finish installing.
Modifying the Express.js Project Output
To confirm your project is running properly, let’s modify the default homepage output.
Edit the
routes/index.js
FileExpress.js projects typically handle different URL requests via route files. Open
routes/index.js
inside your project directory. This file handles GET requests to the root path/
. Change the code so it no longer renders the default Pug template, but simply sends a text response.javascriptvar express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { // Change to send a text response res.send('Hello ServBay!'); }); module.exports = router;
1
2
3
4
5
6
7
8
9
10Save the file.
Entering Development Mode
During development, you typically want to run a local server to see your changes in real-time. You can start Express.js’s built-in HTTP server with the npm start
command.
Run the Development Server
In the root of your
servbay-express-app
project, run the following command to start the development server. Here, you set thePORT
environment variable (using8585
) andDEBUG
variable to enable debug output.bashcd /Applications/ServBay/www/servbay-express-app PORT=8585 DEBUG=servbay-express-app:* npm start
1
2The terminal will display that the Express.js app is listening on port
8585
.Configure ServBay Website Reverse Proxy
Since the Express.js app runs on a custom port (8585) instead of the standard web ports (80/443), you’ll need to use ServBay’s Websites feature to set up a reverse proxy. The ServBay web server (Caddy by default) will listen on 80/443 and forward requests for a specific domain to the Express.js app running at
127.0.0.1:8585
.Open the ServBay Control Panel, switch to the Websites tab, and add a new website with these settings:
- Name:
My first Express.js dev site
(an easy-to-identify name) - Domain:
servbay-express-test.servbay.demo
(using a.servbay.demo
domain enables automatic HTTPS via ServBay’s User CA) - Website Type: select
Reverse Proxy
- IP:
127.0.0.1
(orlocalhost
) - Port:
8585
(the port your Express.js app listens on)
Save and apply your changes in ServBay. ServBay will automatically configure the web server and generate SSL certificates for
.servbay.demo
domains.For detailed steps, refer to ServBay’s documentation on Adding Node.js Development Websites.
- Name:
Access Your Development Website
Open your browser and navigate to
https://servbay-express-test.servbay.demo
. The ServBay web server receives the request and, via reverse proxy, forwards it to your Express.js app running on port 8585. You should see the page displaying "Hello ServBay!".Thanks to ServBay’s support for custom domains and free SSL certificates (including automatic HTTPS for
.servbay.demo
domains), you can easily use HTTPS in your local development, closely mirroring production environments and helping you catch potential issues earlier.
Deploying a Production Version
Once your Express.js project is complete, you’ll want to prepare it for production deployment. Simulating a production environment locally helps you thoroughly test your application.
Prepare the Production Environment
Typically, Express.js projects set the
NODE_ENV
environment variable toproduction
in production environments, altering the behavior of some libraries (disabling debug modes, optimizing performance, etc.). Ensure your project code responds correctly toNODE_ENV=production
.Run the Production Server
From your
servbay-express-app
root, start the server simulating a production environment. Here we use a different port (e.g.,8586
) to differentiate from development, and setNODE_ENV
toproduction
.bashcd /Applications/ServBay/www/servbay-express-app PORT=8586 NODE_ENV=production npm start
1
2The terminal will show the server running on port
8586
.Configure ServBay Website Reverse Proxy (Production)
Similar to development mode, set up another ServBay reverse proxy for the production version.
Open the ServBay Control Panel, switch to the Websites tab, and add a new website with these settings:
- Name:
My first Express.js production site
- Domain:
servbay-express-test-prod.servbay.demo
(or any other domain you prefer for the production simulation) - Website Type: select
Reverse Proxy
- IP:
127.0.0.1
- Port:
8586
(the production app’s port)
Save and apply your changes.
- Name:
Access Your Production Website
Open your browser and navigate to the domain you’ve configured for production simulation, e.g.,
https://servbay-express-test-prod.servbay.demo
. You’ll access your Express.js production instance via ServBay’s reverse proxy on port 8586, making it easy to test your app in a simulated production environment locally.
Database Connections
ServBay provides various database packages for local development, including MariaDB, PostgreSQL, MongoDB, and Redis. If you’ve enabled these databases in ServBay, your Express.js project can connect to them easily. ServBay typically sets default users and passwords, such as root
/password
for MariaDB/MySQL, user
/password
with default database servbay_default
for PostgreSQL, etc. Check ServBay’s database interface or documentation for specifics.
Here’s how to connect these databases within your Express.js project. Make sure you have installed the relevant Node.js drivers using npm install <package-name>
.
Connecting to MongoDB
First, install the
mongoose
driver (a popular ORM):bashnpm install mongoose
1Then, in your project code (for example, in
app.js
or a separate DB config file), import and connect:javascriptvar mongoose = require('mongoose'); // Connect to a local MongoDB instance, database name servbay-express-app // ServBay’s default MongoDB setup requires no auth mongoose.connect('mongodb://localhost/servbay-express-app', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('MongoDB connection error:', err));
1
2
3
4
5
6
7
8
9
10Make sure the MongoDB package is running in ServBay.
Connecting to Redis
First, install the
redis
client:bashnpm install redis
1Then in your project, import and connect:
javascriptvar redis = require('redis'); // ServBay runs Redis on localhost:6379 with no password by default var client = redis.createClient({ host: 'localhost', port: 6379 }); client.on('connect', function() { console.log('Connected to Redis'); }); client.on('error', function (err) { console.log('Redis Error: ' + err); }); // Example: set and get a key // client.set('mykey', 'Hello from Express!', redis.print); // client.get('mykey', function(err, reply) { // if (err) throw err; // console.log(reply); // Prints "Hello from Express!" // }); // Use the client object for Redis operations as needed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23Make sure the Redis package is running in ServBay.
Connecting to MariaDB / MySQL
ServBay supports both MariaDB and MySQL. You typically connect using the
mariadb
ormysql2
npm packages (here we usemariadb
, which also works for MySQL).First, install
mariadb
ormysql2
:bashnpm install mariadb # or npm install mysql2
1Then, use ServBay’s default credentials to connect. For MariaDB/MySQL, the default
root
password ispassword
.javascriptvar mariadb = require('mariadb'); // ServBay runs MariaDB/MySQL on localhost:3306 by default var pool = mariadb.createPool({ host: 'localhost', port: 3306, // default port user: 'root', // default user for ServBay password: 'password', // default password for ServBay database: 'servbay_express_app', // create this database in ServBay connectionLimit: 5 // pool size }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB/MySQL"); // Use conn object to run queries // conn.query("SELECT 1").then(...).catch(...).finally(() => conn.release()); conn.release(); // Release connection back to pool after use }) .catch(err => { console.log("Not connected due to error: " + err); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21You may need to create the
servbay_express_app
database in ServBay first (via tools like phpMyAdmin, Adminer, etc., accessible through ServBay). Ensure the MariaDB or MySQL package is running in ServBay.Connecting to PostgreSQL
First, install the PostgreSQL client library
pg
:bashnpm install pg
1Then, use ServBay’s default credentials for connection: user
user
, passwordpassword
, default databaseservbay_default
.javascriptvar { Pool } = require('pg'); // ServBay runs PostgreSQL on localhost:5432 by default var pool = new Pool({ user: 'user', // default ServBay user host: 'localhost', database: 'servbay_default', // default db or another you created password: 'password', // default password port: 5432, // default port }); pool.connect((err, client, done) => { if (err) { console.error('PostgreSQL connection error:', err); return; } console.log('Connected to PostgreSQL'); // Use client to run queries // client.query('SELECT NOW()', (err, res) => { ... done(); }); done(); // Release client }); // Or with async/await // try { // const client = await pool.connect(); // console.log('Connected to PostgreSQL'); // // const res = await client.query('SELECT NOW()'); // // console.log(res.rows[0]); // client.release(); // } catch (err) { // console.error('PostgreSQL connection error:', err); // }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31Be sure the PostgreSQL package is running in ServBay.
Summary
By following these steps, you have successfully created, configured, and run an Express.js project using ServBay. You’ve learned how to:
- Initialize a project with
express-generator
. - Run your Express.js app on a custom port.
- Configure a reverse proxy via ServBay's Websites feature to access your Node.js app through standard HTTP/S ports.
- Connect to various popular databases in the ServBay environment.
ServBay greatly simplifies the setup and management of your local Node.js (Express.js) development environment, enabling you to focus more on your code. Additional ServBay features, such as automatic SSL certificates, website backups, and log viewing, can further streamline your local development workflow.