w3resource

Using Neon PostgreSQL: Setup, Features, and Examples


Neon PostgreSQL: A Modern Serverless Database for the Cloud

Neon is a serverless and cloud-native PostgreSQL platform designed for scaling and efficiency. It provides the full power of PostgreSQL without the need to manage server resources. Neon’s architecture makes it a highly scalable solution, offering features like auto-scaling, low-latency connections, and cost efficiency for applications with dynamic workloads. This makes it an ideal choice for cloud environments, especially when working with modern, serverless architectures.

Description

Neon PostgreSQL is a fully-managed PostgreSQL service that focuses on high performance and elasticity. Its serverless nature allows it to scale dynamically, making it perfect for applications with varying database demands. Neon also integrates well with popular cloud platforms, providing a seamless developer experience for managing PostgreSQL databases in the cloud.

Key Features of Neon PostgreSQL:

  • Serverless Architecture: No need for provisioning servers. Neon handles scaling automatically based on usage.
  • Auto-Scaling: Neon adjusts resource allocation based on your workload in real-time, which is ideal for applications with fluctuating traffic.
  • Multi-Region Support: Neon offers low-latency data access by deploying across multiple cloud regions, enhancing global application performance.
  • Cost-Effective: Pay only for what you use, as Neon charges based on storage and compute power consumed, not fixed instance sizes.
  • Compatibility with PostgreSQL: Supports standard PostgreSQL functionality, allowing easy migration from self-hosted or managed PostgreSQL services.

Getting Started with Neon PostgreSQL

To start using Neon PostgreSQL, follow these steps to set up a database and connect it to your application.

Example Setup Process

1. Create a Neon Account and Database:

  • Sign up on the Neon platform.
  • Create a new PostgreSQL database, and note the connection details provided by Neon (host, port, database name, user, and password).

2. Set Up Environment Variables:

  • Store the database connection details securely using environment variables.
  • # Example of setting environment variables for Neon connection
    export NEON_DATABASE_URL=postgres://username:password@host:port/database
    
  • Replace username, password, host, port, and database with your Neon PostgreSQL database credentials.

3. Connect to Neon PostgreSQL Using a Client:

In a Node.js project, use the pg library to connect to Neon.

Code:

// Import the pg library
const { Client } = require('pg');

// Create a client instance with the Neon connection URL
const client = new Client({
  connectionString: process.env.NEON_DATABASE_URL,
  ssl: { rejectUnauthorized: false }
});

// Connect to the database and query data
client.connect()
  .then(() => console.log('Connected to Neon PostgreSQL'))
  .then(() => client.query('SELECT NOW()')) // Example query
  .then(res => console.log('Current time:', res.rows[0]))
  .catch(err => console.error('Connection error', err.stack))
  .finally(() => client.end());

Explanation:

  • This script connects to the Neon PostgreSQL database using the provided connection URL.
  • It performs a simple query to get the current time from the database.

Example Query for Neon PostgreSQL

Here is an example function to add a new user to a hypothetical users table:

Code:

async function addUser(name, email) {
  try {
    await client.connect();
    const res = await client.query(
      'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *', 
      [name, email]
    );
    console.log('User added:', res.rows[0]);
  } finally {
    client.end();
  }
}
addUser('Jane Doe', '[email protected]').catch(console.error);

Explanation:

  • This function connects to the Neon database, inserts a new user, and logs the added user’s details to the console.

Notes:

  • SSL Requirement: Neon databases often require SSL connections. Ensure the SSL option is enabled in your connection configuration to prevent connection issues.
  • Error Handling: Implement error handling for production environments to manage network disruptions or connection timeouts.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/neon-postgres.php