'Heroku with Strapi, Application is not using production database

I've deployed my app to Heroku. It gives an Application Error message upon visit.

The logs gave me this:

[2021-02-15T01:04:05.882Z] debug ⛔️ Server wasn't able to start properly.
[2021-02-15T01:04:05.883Z] error Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)

Which according to my guess, is that its trying to use local database. I think the app is not using the database.js located in config/env/production. The application runs fine with heroku local.

Below is the database.js I set for production env:

const parse = require("pg-connection-string").parse;
const config = parse(process.env.DATABASE_URL);

module.exports = ({ env }) => ({
  defaultConnection: "default",
  connections: {
    default: {
      connector: "bookshelf",
      settings: {
        client: "postgres",
        host: config.host,
        port: config.port,
        database: config.database,
        username: config.user,
        password: config.password,
        ssl: {
          rejectUnauthorized: false,
        },
      },
      options: {
        ssl: true,
      },
    },
  },
});

Creating and printing the config var on heroku console results in expected values.



Solution 1:[1]

For some reason the deployment method in the strapi docs to heroku does not seem to work when you initially have set up your local database as Postgres. I had the same problem as you and I fixed it using the NODE_ENV env variable. Instead of creating a new production database config file in ./config/production/database.js you can simply extend the config file in ./config/database.js with the prod config and decide based on what NODE_ENV is set which one to return.

As example:

module.exports = ({ env }) => {
  const parse = require("pg-connection-string").parse;
  const config = parse(env("DATABASE_URL", "127.0.0.1"));

  const devConfig = {
    client: "postgres",
    connection: {
      host: env("DATABASE_HOST", "127.0.0.1"),
      port: env.int("DATABASE_PORT", 5432),
      database: env("DATABASE_NAME", "db_name"),
      user: env("DATABASE_USERNAME", "root"),
      password: env("LOCAL_DB_PASSWORD"),
      ssl: env.bool("DATABASE_SSL", false),
    },
  };

  const prodConfig = {
    client: "postgres",
    connection: {
      host: config.host,
      port: config.port,
      database: config.database,
      user: config.user,
      password: config.password,
      ssl: {
        rejectUnauthorized: false,
      },
    },
    debug: false,
  };

  return 
      env("NODE_ENV", "development") === "production" ? prodConfig : devConfig
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nickfis