How to Securely Query Postgres in Node.js

How to Securely Query Postgres in Node.js

In this article, we discuss how to use both Postgres ORM and raw SQL in order to securely query data from a Postgres database with Node.js.

When you’re querying Postgres, you need to choose between:

  • Using an ORM. This gives you “native” feeling APIs to query the database.
  • Using raw SQL. This gives you the ultimate flexibility and performance and gives you more transferable skills. It’s always helpful to know how to write SQL.

Postgres ORM

If you want to use an ORM to query Postgres, I recommend using https://typeorm.io. If you’re starting with a fresh project, you can use their typeorm init CLI command:

npx typeorm init --name MyProject --database postgrescd MyProject && yarn

You’ll then need to edit ormconfig.json to add your database connection options. You’ll need to add a file in src/entity for each table in your database.

You may also like: Restful API with NodeJS, Express, PostgreSQL, Sequelize, Travis, Mocha, Coveralls and Code Climate.

You can then use a JavaScript API to create records in your database:

import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";

async function createPhoto() {  
  const connection = await createConnection({    
    type: 'postgres',    
    url:  process.env.DATABASE_URL || 'postgres://test:[email protected]/test' 
  });  

  const photo = new Photo();  
  photo.name = "Me and Bears";  
  photo.description = "I am near polar bears";  
  photo.filename = "photo-with-bears.jpg";  
  photo.views = 1;  
  photo.isPublished = true;  
  const {id} = await connection.manager.save(photo);  

  console.log("Photo has been saved. Photo id is", photo.id);}

createPhoto();

There are advantages to this approach (the biggest being that it supports strong types), but I personally feel that it makes the code pretty hard to read/follow, and the skills you learn on TypeORM will be of no use if you move to a different ORM

Raw SQL

I believe that the simplest and easiest way to query Postgres is to directly write the SQL that will be run against your database.

“Using SQL directly, means there’s nothing to configure”

yarn add @databases/pg

You’ll need to set theDATABASE_URL environment variable to a database connection string.

import connect, {sql} from '@databases/pg';

const db = connect();

export async function getAllUsers() {
  return await db.query(sql`SELECT * FROM users;`);
}

export async function getUserById(userId) {
  return (await db.query(sql`
    SELECT * FROM users WHERE user_id=${userId}
  `))[0];
}

export async function createUser(u) {
  return (await db.query(sql`
    INSERT INTO users (name, email)
    VALUES (${u.name}, ${u.email})
    RETURNING user_id;
  `))[0].user_id;
}

export async function deleteUserById(userId) {
  await db.query(sql`DELELTE FROM users WHERE user_id=${userId}`);
}

export async function updateUserById(userId, u) {
  await db.query(sql`
    UPDATE users
    SET name=${u.name}, email=${u.email}
    WHERE user_id=${userId}
  `);
}

export async function upsertUser(userId, u) {
  return (await db.query(sql`
    INSERT INTO users (user_id, name, email)
    VALUES (${userId}, ${u.name}, ${u.email})
    ON CONFLICT (user_id)
    DO UPDATE SET name=${u.name}, email={u.email}
    RETURNING *;
  `))[0];
}

N.B. The [@databases](https://www.atdatabases.org/) library does not just concatenate your user input into a string of SQL, it separates your parameters from the actual query, and uses prepared statements to run the query. It throws a clear runtime exception if you forget to tag your sql with the sql tag. This means it’s virtually impossible for you to introduce SQL Injection vulnerabilities by accident.

Conclusion

For most projects, I recommend querying your Postgres database directly using @databases/pg. It gives you the ultimate flexibility. If you need TypeScript types, I recommend declaring the types along with the SQL that queries. TypeScript isn’t currently able to check that the types match your database schema, but at least if they’re in the same file, you’ll probably remember to keep them in sync.

Thank for reading! If you liked this post, share it with all of your programming buddies!

node-js postgresql sql javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Introduction to Structured Query Language SQL pdf

SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Develop this one fundamental skill if you want to become a successful developer

Throughout my career, a multitude of people have asked me&nbsp;<em>what does it take to become a successful developer?</em>

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.