How to Integrate H2 Database with Express and Node.js

Updated: December 28, 2023 By: Guest Contributor Post a comment

In this tutorial, we’ll learn how to integrate the H2 database with an Express application running on Node.js. H2 is a Java-based SQL database which is often used for development and testing purposes due to its in-memory nature. However, since H2 is designed to be used with Java applications, integrating it directly with a Node.js application is not straightforward. Therefore, we will make use of an API-based approach to communicate with H2 database, which is running separately.

Step 1: Set up your Node.js and Express project structure.

$ npm init -y
$ npm install express --save

Step 2: Set up an H2 database and start it. Make sure you have Java installed and download the H2 database from the official website. Start H2 with the following command:

$ java -cp h2*.jar org.h2.tools.Server

Step 3: Access the H2 Console and create a new table.

http://localhost:8082

Step 4: Write a simple API in your Express application to communicate with H2 using an HTTP client or JDBC-like bridge module for Node.js.

const express = require('express');
const app = express();
const { Pool } = require('pg');
const pool = new Pool({
  // Connection parameters
});
app.get('/data', async (req, res) => {
  const result = await pool.query('SELECT * FROM YOUR_TABLE');
  res.json(result.rows);
});
app.listen(3000, () => console.log('Server running on port 3000'));

Remember that in the above pseudo code, we use PostgreSQL client for Node.js as an example. In reality, you would need to find a JDBC bridge or a module that allows you to execute SQL commands against H2 database, since H2 is not natively supported in Node.js.

Here’s a complete code example:

const express = require('express');
const app = express();
// Include the JDBC bridge module
// Setup the H2 database connection

app.get('/data', (req, res) => {
  // Your query logic here
});

app.listen(3000, () => {
  console.log('Server is up and running on port 3000.');
});

The example above is purposely abstract because direct integration between H2 and Node.js isn’t typically done. Usually, an intermediate service layer is written in Java to handle the database operations, and Node.js would communicate with this service over HTTP.

In conclusion, integrating H2 with Express and Node.js requires running the H2 database as a separate service and interacting with it over HTTP. As there is no direct support for H2 in Node.js, you either need to find a suitable bridge module or build a RESTful API layer using Java to perform operations on the H2 database.