Vite is a modern frontend build tool that’s gaining popularity for its speed and simplicity, while PostgreSQL is a powerful, open-source relational database. Combining the two can help you build dynamic, data-driven web applications. In this guide, we’ll walk you through the process of connecting Vite to PostgreSQL using Node.js and Express.

Why Connect Vite to PostgreSQL?

Vite is excellent for building fast and efficient frontend applications, but it doesn’t handle database interactions directly. By setting up a backend server with Node.js and Express, you can bridge the gap between your Vite frontend and PostgreSQL database. This setup allows you to:

  • Fetch and display data from PostgreSQL in your Vite app.
  • Handle CRUD (Create, Read, Update, Delete) operations seamlessly.
  • Build full-stack applications with a modern tech stack.

1. Initialize a Vite Project

Start by creating a new Vite project. Open your terminal and run:

npm create vite@latest my-vite-app
cd my-vite-app
npm install

This will set up a new Vite project in the my-vite-app directory.

2. Set Up a Node.js Backend

Next, create a backend directory to handle your server logic:

mkdir backend
cd backend
npm init -y
npm install express pg dotenv

This initializes a new Node.js project and installs the necessary dependencies:

  • Express: A web framework for Node.js.
  • pg: A PostgreSQL client for Node.js.
  • dotenv: A package to manage environment variables.

Step 2: Configure PostgreSQL Connection

1. Store Database Credentials

Create a .env file in the backend directory to securely store your PostgreSQL credentials:

PGHOST=your_host
PGUSER=your_user
PGPASSWORD=your_password
PGDATABASE=your_database
PGPORT=your_port

2. Set Up the Database Connection

In the backend/index.js file, configure the connection to PostgreSQL:

const express = require('express');
const { Pool } = require('pg');
require('dotenv').config();

const app = express();
const port = 3000;

const pool = new Pool({
  host: process.env.PGHOST,
  user: process.env.PGUSER,
  password: process.env.PGPASSWORD,
  database: process.env.PGDATABASE,
  port: process.env.PGPORT,
});

app.get('/api/data', async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM your_table');
    res.json(result.rows);
  } catch (err) {
    console.error(err);
    res.status(500).send('Server Error');
  }
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

This code sets up an Express server that connects to PostgreSQL and fetches data from a table.

Step 3: Connect Frontend to Backend

1. Start the Backend Server

Run the backend server using:

node backend/index.js

2. Fetch Data in Your Vite App

In your Vite app, update src/App.jsx or src/App.js to fetch data from the backend:

import React, { useEffect, useState } from 'react';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('http://localhost:3000/api/data')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  return (
    <div>
      <h1>Data from PostgreSQL</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

This code fetches data from the backend and displays it in your Vite app.

Step 4: Run Your Vite App

Start the Vite development server:

npm run dev

Open your browser and navigate to http://localhost:5173 (or the port Vite is running on) to see your app in action.

Disclaimer

Sengideons.com does not host any files on its servers. All point to content hosted on third-party websites. Sengideons.com does not accept responsibility for content hosted on third-party websites and does not have any involvement in the same.

LEAVE A REPLY

Please enter your comment!
Please enter your name here