Connect from Knex to Neon
Learn how to connect to Neon from Knex
Knex is an open-source SQL query builder for Postgres. This guide covers the following topics:
Connect to Neon from Knex
To establish a basic connection from Knex to Neon, perform the following steps:
-
Retrieve your Neon connection string. In the Connection Details widget on the Neon Dashboard, select a branch, a user, and the database you want to connect to. A connection string is constructed for you. The connection string includes the user name, password, hostname, and database name.
-
Update the Knex's initialization in your application to the following:
-
Add a
DATABASE_URL
variable to your.env
file and set it to the Neon connection string that you copied in the previous step. We also recommend adding?sslmode=require
to the end of the connection string to ensure a secure connection.Your setting will appear similar to the following:
Use connection pooling with Knex
Serverless functions can require a large number of database connections as demand increases. If you use serverless functions in your application, we recommend that you use a pooled Neon connection string, as shown:
A pooled Neon connection string adds -pooler
to the endpoint ID, which tells Neon to use a pooled connection. You can add -pooler
to your connection string manually or copy a pooled connection string from the Connection Details widget on the Neon Dashboard. Use the Pooled connection checkbox to add the -pooler
suffix.
Performance tips
This section outlines performance optimizations you can try when using Knex with Neon.
Enabling NODE_PG_FORCE_NATIVE
Knex leverages a node-postgres Pool instance to connect to your Postgres database. Installing pg-native and setting the NODE_PG_FORCE_NATIVE
environment variable to true
switches the pg
driver to pg-native
, which can produce noticeably faster response times according to some users.
Replacing query parameters
You may be able to achieve better performance with Knex by replacing any parameters you've defined in your queries, as performed by the following function, for example:
You can try this optimization yourself by downloading our Get started with Knex example and running npm run test
.
Examples
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. Users on paid plans can open a support ticket from the console. For more detail, see Getting Support.