There are two options for connecting to Railway's postgres database. Using a connection string or a psql command. This tutorial is going to cover the former(connection string).
1. Get a postgres database running
First thing's first, let's get the database up and running.
1.1. Go to https://railway.app and click the "Start a New Project" button.
1.2. Choose the "Provision PostgreSQL" option and wait for it to finish setting up.
1.3. Select PostgreSQL card.
1.4. Go to the "Connect" tab.
1.5. Copy the "Postgres Connection URL" provided for use in the express app
2. Create and setup the express app
2.1. Initialise a javascript project with npm in the project directory
npm init -y
2.2. Install express
npm install express
2.3. Create express app file and setup express
2.4. Initialise the express app
// In index.js
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello, World!");
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Okay now to the main idea of this post.
3. Connect postgreSQL with express app via node-postgres
3.1. Install node-postgres for interfacing with the database
npm install pg
3.2. Create a separate file for the node-postgres setup.
3.3. Initialise node-postgres connection passing the connection string from the database as part of the new Pool
object
// In db.js
const { Pool } = require("pg");
// The secret connection string you copied earlier
const connectionString =
"postgresql://postgres:dr75i6HaC0sDZDTjtLCt@containers-us-west-37.railway.app:6233/railway";
const pool = new Pool({
connectionString,
});
module.exports = pool;
3.4. Start making calls to your db via express. See example of getting posts from and existing post table
// In index.js
const express = require("express");
const pool = require("./db");
const app = express();
app.get("/", (req, res) => {
res.send("Hello, World!");
});
app.get("/posts", async (req, res) => {
const posts = await pool.query("SELECT * FROM posts;");
res.send({ posts });
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
That is it. You can find the code used in this tutorial at this github repo
Top comments (1)
thanks was helpful