Connect to a database

Fixie is a proxy service that provides static IP addresses that can be used to establish any TCP connection, including database connections.

Fixie provides both HTTP proxies and SOCKS proxies. To connect to a database, we will use a SOCKS proxy.

We recommend storing your credentials in a FIXIE_SOCKS_HOST environment variable. If you use Fixie's add-ons for Vercel or Heroku, this environment variable will be set automatically.

Remember to keep sensitive configuration values, like credentials, out of source control.

Connecting by configuring your database driver

Some database drivers and libraries support SOCKS proxies natively. An example is Mongoose, a popular Javascript ODM for MongoDB:

const mongoose = require('mongoose');
const fixieData = process.env.FIXIE_SOCKS_HOST.split(new RegExp('[/(:\\/@/]+'));

mongoose.connect(process.env.DB_CONNECTION,
    {
      proxyUsername: fixieData[0],
      proxyPassword: fixieData[1],
      proxyHost: fixieData[2],
      proxyPort: fixieData[3]
     },
    (error) => {
      if(error){
        console.log(error)
      }
      console.log('Connected to database')}
)

Conversely, with Javascript's postgresql driver, pg, we would configure the the driver to use a SocksConnection stream:

const pg = require('pg');
const SocksConnection = require('socksjs');

const fixieUrl = process.env.FIXIE_SOCKS_HOST;
const fixieValues = fixieUrl.split(new RegExp('[/(:\\/@)/]+'));

const pgServer = {
  host: 'YOUR-HOST',
  port: 5432
};

const fixieConnection = new SocksConnection(pgServer, {
  user: fixieValues[0],
  pass: fixieValues[1],
  host: fixieValues[2],
  port: fixieValues[3],
});

const connectionConfig = {
  user: 'YOUR-DB-USERNAME',
  password: 'YOUR-DB-PASSWORD',
  database: 'YOUR-DATABASE',
  stream: fixieConnection,
  ssl: true // Optional, depending on db config
};

var client = new pg.Client(connectionConfig);

client.connect(function (err) {
  if (err) throw err;
  client.query('SELECT 1+1 as test1', function (err, result) {
    if (err) throw err;
    console.log(result.rows[0]);
    client.end(function (err) {
      if (err) throw err;
    });
  });
});

Many popular database drivers and ORMs support SOCKS proxies through an approach like the two above. For those that do not, we offer Fixie-Wrench.

Connecting using Fixie-Wrench

Fixie-Wrench is a utility that does port-forwarding, allowing your application to connect to any remote database as if it were running locally. Connections are tunneled through Fixie Socks such that every connection comes from a stable set of static IP addresses.

Fixie-Wrench is available on GitHub.

You may also consult the fixie-wrench Heroku example app or Koyeb example app

Having issues? Please reach out to our team here.