Getting Started with Next.js: Building a Simple Application with PostgreSQL Integration

Are you looking to dive into building web applications with Next.js? Next.js is a powerful React framework that makes it easy to create server-rendered React applications. Its simplicity and versatility make it a popular choice for developers wanting to build dynamic and performant web applications. In this guide, we’ll walk through the steps to get started with Next.js and integrate it with a PostgreSQL database to build a simple application.

Why Next.js?

Next.js offers several benefits that make it an excellent choice for web development:

  1. Server-side rendering (SSR): Next.js allows you to pre-render pages on the server, which improves performance and SEO.
  2. Zero configuration: Next.js comes with built-in support for Webpack, Babel, and other tools, so you can focus on writing code rather than configuring build tools.
  3. Automatic code splitting: Next.js automatically splits your code into smaller chunks, so only the necessary code is loaded for each page, improving performance.
  4. API routes: Next.js allows you to create API routes alongside your pages, making it easy to build backend functionality within your application.

Now, let’s dive into building a simple Next.js application with PostgreSQL integration.

Step 1: Setting Up the Project

First, let’s create a new Next.js project. Make sure you have Node.js installed on your system.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-next-app my-next-app
cd my-next-app
npx create-next-app my-next-app cd my-next-app
npx create-next-app my-next-app
cd my-next-app

Do Not Select App Router when given the option

Step 2: Installing Dependencies

Next, we need to install the necessary dependencies for PostgreSQL integration. We’ll use pg library for connecting to PostgreSQL.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install pg
npm install pg
npm install pg

Step 3: Creating PostgreSQL Database

For this example, let’s assume you have a PostgreSQL database set up locally. Create a table named users with columns id, name, and email.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) );
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

Step 4: Connecting to PostgreSQL

Now, let’s create a file named db.js to handle the database connection.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// db.js
const { Pool } = require('pg');
const pool = new Pool({
user: 'your_username',
host: 'localhost',
database: 'your_database_name',
password: 'your_password',
port: 5432,
});
module.exports = pool;
// db.js const { Pool } = require('pg'); const pool = new Pool({ user: 'your_username', host: 'localhost', database: 'your_database_name', password: 'your_password', port: 5432, }); module.exports = pool;
// db.js
const { Pool } = require('pg');

const pool = new Pool({
  user: 'your_username',
  host: 'localhost',
  database: 'your_database_name',
  password: 'your_password',
  port: 5432,
});

module.exports = pool;

Step 5: Fetching Data from PostgreSQL

Create a page named users.js to fetch data from the users table and display it.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// pages/users.js
import pool from '../db';
export default function Users({ users }) {
return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
</div>
);
}
export async function getServerSideProps() {
try {
const result = await pool.query('SELECT * FROM users');
const users = result.rows;
return { props: { users } };
} catch (err) {
console.error('Error fetching data:', err);
return { props: { users: [] } };
}
}
// pages/users.js import pool from '../db'; export default function Users({ users }) { return ( <div> <h1>Users</h1> <ul> {users.map(user => ( <li key={user.id}> {user.name} - {user.email} </li> ))} </ul> </div> ); } export async function getServerSideProps() { try { const result = await pool.query('SELECT * FROM users'); const users = result.rows; return { props: { users } }; } catch (err) { console.error('Error fetching data:', err); return { props: { users: [] } }; } }
// pages/users.js
import pool from '../db';

export default function Users({ users }) {
  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export async function getServerSideProps() {
  try {
    const result = await pool.query('SELECT * FROM users');
    const users = result.rows;
    return { props: { users } };
  } catch (err) {
    console.error('Error fetching data:', err);
    return { props: { users: [] } };
  }
}

Step 6: Running the Application

Start the Next.js development server and navigate to http://localhost:3000/users to see the list of users fetched from the PostgreSQL database.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm run dev
npm run dev
npm run dev

Congratulations! You’ve built a simple Next.js application with PostgreSQL integration. This example demonstrates the basic setup for connecting Next.js with a PostgreSQL database and fetching data to display on a page. From here, you can expand and customize the application according to your requirements.

Next.js provides a powerful platform for building modern web applications, and integrating it with databases like PostgreSQL opens up a world of possibilities for creating dynamic and data-driven applications. Happy coding!