node.jspostgresqlnext.jsnode-pg-pool

Setting up pg-pool connection on Next.js initialization: ERROR: "Can't resolve 'fs'


I'm trying to use npm pg with pg-pool in my Next.js application.

I'm new to pooling connections but I gathered that I need to establish a pool connection whenever my Next.js server is initialized and I need to pass that connection as a module around my application.

From pg-pool docs:

a note on instances
The pool should be a long-lived object in your application. Generally you'll want to instantiate one pool when your app starts up and use the same instance of the pool throughout the lifetime of your application. If you are frequently creating a new pool within your code you likely don't have your pool initialization code in the correct place.

So, I created file my-app/lib/db.js to initialize my connection and hopefully pass that around my application whenever I need to run a query.

However, when I attempt to import { Pool } from 'pg'; I get an error: Module not found: Can't resolve 'fs'

I found this question with the understanding now that..

You can't use Node.js libraries that use fs in Next.js Middleware. Try using a client-side library instead.

So, my question is, how can I initiate a postgres-pool connection on a Next.js server node and route all queries through it? Do I need use a different package? Really not sure where to place this in the Next.js architecture.


Solution

  • If you only import it with "import { Pool } from 'pg';" in a component (not an API route) without calling the "Pool" object inside "getServerSideProps" or "getStaticProps" it will fail because Nextjs will include the "Pool" object in the client bundle and this way you will try to import a server-side module "fs" in the browser.

    If you call the "Pool" in "getServerSideProps" or "getStaticProps" Nextjs will know NOT to include the "Pool" object in the client bundle and the problem will be solved.

    There is a very good explanation here: https://maikelveen.com/blog/how-to-solve-module-not-found-cant-resolve-fs-in-nextjs