This guide describes how to connect Neon in a Phoenix application. Ecto provides an API and abstractions for interacting databases, enabling Elixir developers to query any database using similar const...
Pre-built prompt for connecting Phoenix applications to Lakebase Postgres
This guide describes how to connect Neon in a Phoenix application. Ecto provides an API and abstractions for interacting databases, enabling Elixir developers to query any database using similar constructs.
It is assumed that you have a working installation of Elixir.
Create a Neon project
If you do not have one already, create a Neon project. Save your connection details including your password. They are required when defining connection settings.
Navigate to the Projects page in the Neon Console.
Click New Project.
Specify your project settings and click Create Project.
Store your Neon credentials
Add a .env file to your project directory and add your Neon connection string to it. You can find your connection string by clicking the Connect button in the Console nav to open the Connect to your branch modal. For more information, see Connect from any application.
The :ssl option is required to connect to the database. Postgrex, since v0.18, verifies the server SSL certificate and you need to select CA trust store using :cacerts or :cacertfile options. You can use the OS-provided CA store by setting cacerts: :public_key.cacerts_get(). While not recommended, you can disable certificate verification by setting ssl: [verify: :verify_none].
This guide configures the test environment for completeness but doesn't cover running tests. For production workflows, consider using Neon branches instead of a separate test database. Branches provide isolated, cost-effective copies of your database that are ideal for testing and CI/CD pipelines.
Install dependencies and create databases
Install the dependencies:Bash
mix deps.get
Create the development and test databases:Bash
mix ecto.create
MIX_ENV=test mix ecto.create
The first command creates the development database (neondb). The second creates the test database (with_phoenix_test).
Build and run the Phoenix application
To compile the app in production mode, run the following command:
Bash
MIX_ENV=prod mix compile
To compile assets for the production mode, run the following command:
Bash
MIX_ENV=prod mix assets.deploy
For each deployment, a secret key is required for encrypting and signing data. Run the following command to generate the key:
Bash
mix phx.gen.secret
When you run the following command, you can expect to see the Phoenix application at http://localhost:4001: