0

I am probably missing something very obvious here, but I keep getting the following error when trying to use Postgres from a newly created React app

Module not found: Can't resolve 'dns' in '/Users/tarek/test/node_modules/pg/lib'

Here are the steps to reproduce:

  1. Create a fresh React app using create-react-app
  2. Add the Postgres module using npm install pg --save
  3. Add the following line to App.js: const { Client } = require('pg');
  4. Type npm run start and you'll get the above error.

What am I missing here?

**Node version: v8.12.0

** package.json

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "pg": "^7.4.3",
    "react": "^16.5.1",
    "react-dom": "^16.5.1",
    "react-scripts": "1.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

1 Answer 1

3

The issue is that React apps are meant to run in the browser, and browsers can't access databases directly. Even if you did find a way to do this, it would only work locally and not in production. Consider that if the database is on your machine and your app available on the internet, there would be no way for a remote user to get access to the data on your machine in the way you are describing.

In order to use a database with React, you'll need to set up a server—possibly written in Node (with Express)—that will serve your application and data for it.

The server receives requests from different users and responds with the appropriate resources. For example if they go to your website (e.g. example.com), your server should respond with index.html for your project (in this case it would be the index.html for your React app). Then to get data from your database, you can set up an api with routes like example.com/api/model/1 so that your react app can request the instance of model with id 1 from your server, which will grab it from the database and send it over to the React app.

Look into the MERN (Mongo Express React Node) stack for more detail on how all these work together. Even with Postgres the process will be pretty much the same as with Mongo.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Henry, that was really helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.