Server Side JavaScript to client side Javascript conflict: ‘Uncaught ReferenceError: require is not defined’

I am a student working on a final project for my class and running into an issue connecting my database and website. I have asked my teacher and he is unsure how to resolve this issue, so I am turning to the community for help.

I have successfully connected and interacted with my PostgreSQL database through the node package ‘pg’ in my database.js file.

const { Client } = require('pg')

However, when I try to use the connection in my utils.js file I get the ‘Uncaught ReferenceError: require is not defined’ error.

const database = require('./database.js')

In researching this issue I have tried using import instead of require:

// Database is a class object that connects to a database and contains several functions to interact with the database.
import { Database } from "./database.js";

This still results in a require is not defined error, but in the database.js file instead. I then tried importing the ‘pg’ package in the database.js

import { Client } from 'pg';

When I check my connection to the database I get this message:

“SyntaxError: Named export ‘Client’ not found. The requested module ‘pg’ is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export.”

This lead me to try:

import pkg from 'pg';
const { Client } = pkg;

That fixed my connection to my database in the database.js file, but when I try to load a webpage that uses the utils.js file I get this message in the console:

“Uncaught TypeError: Failed to resolve module specifier “pg”. Relative references must start with either “/”, “./”, or “../”.”

I googled the error and it said the “pg” package is not installed, but I double checked and even reinstalled “pg” to no avail.

Thank you for your help.

  • 4

    It makes no sense to access the database from client-side JavaScript.

    – 

  • You need to build an API to communicate between server and client. The client cannot use the database directly (if it were possible, how would you be able to enforce any security boundaries? every visitor would have full control over your database, that doesn’t make sense.) – instead, only the server will talk to your database (after validating everything that came from the untrusted client), while the client will talk to your server via your API.

    – 




  • Perhaps the problem is that your “utils” module has too much stuff in it. Don’t be afraid of tiny modules.

    – 

  • Thank you, with your comments I changed my programs so the data from the client side was filtered and sent to the server side, which handled the SQL commands and everything seems to be working.

    – 

Leave a Comment