Knex/PostgreSQL/CockroachDB in Netlify Functions

I’m trying to connect to a CockroachDB database through Knex, but I get this error from Knex:

Error: Knex: run
$ npm install cockroachdb --save
Cannot find module 'pg'

Note that both cockroachdb and pg (which is what Knex uses to connect to CockroachDB) are installed. This is the dependencies part of package.json in the root of the project:

  "dependencies": {
    "@vendia/serverless-express": "^4.10.1",
    "cockroachdb": "^1.0.3",
    "express": "^4.18.2",
    "knex": "^2.3.0",
    "knex-stringcase": "^1.4.6",
    "pg": "^8.8.0"
  }

This is the code:

const knex = require('knex')
const db = knex({
  client: 'cockroachdb',
  connection: 'postgresql:...'
})

exports.handler = async function(event, context) {
  return {
    statusCode: 200,
    body: JSON.stringify({ hej: 'virker' })
  }
}

Note that it’s not an error that the database URL begins with “postgresql:” - that’s how it works with CockroachDB.

URL: https://hej8.netlify.app/.netlify/functions/index

Did you try to add the following in your netlify.toml:

[functions]
  external_node_modules = ['pg']

Turns out all I needed to do was to use import instead of require (the reason I used require in the first place was that the code was legacy code). And the cockroachdb package is not needed, only pg.

This code works:

import Knex from 'knex'

const db = Knex({
  client: 'cockroachdb',
  ...