How to Get Started with @neondatabaseserverless

Oct 28, 2021 | Programming

@neondatabaseserverless is an innovative PostgreSQL driver tailored for JavaScript and TypeScript, developed by Neon. It supports low-latency connections and is perfect for serverless edge deployments. In this blog post, we’ll walk you through the essential steps to install, configure, and deploy it, along with some troubleshooting insights.

Installation

To get started with @neondatabaseserverless, you need to install it using your preferred JavaScript package manager. You can find it as @neondatabaseserverless on npm and @neonserverless on JSR.

  • Bash command to install with npm: npm install @neondatabaseserverless
  • Bash command to install with JSR: bunx jsr add @neonserverless

If you are using TypeScript, rest assured that types are already included!

Configuring the Connection

To configure, you need the connection string from the Neon console. Set it as an environment variable like this:

DATABASE_URL=postgres:username:password@host.neon.tech/neondb

Usage

For executing one-shot queries, you’ll need to use the neon function which enhances the interaction with the database:

import neon from '@neondatabaseserverless';
const sql = neon(process.env.DATABASE_URL);
const [post] = await sql`SELECT * FROM posts WHERE id = $postId`;

The variable post will now contain your data—either the post itself or undefined if nothing is found. This method is also safe from SQL injection!

Deploying your API

Let’s transform this into a complete API endpoint, which can be deployed on Vercel Edge Functions. Follow these steps:

  1. Create a new file apipost.ts with the following code:
  2. import neon from '@neondatabaseserverless';
    const sql = neon(process.env.DATABASE_URL);
    
    export default async (req: Request, ctx: any) => {
        const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10);
        if (isNaN(postId)) return new Response('Bad request', { status: 400 });
        const [post] = await sql`SELECT * FROM posts WHERE id = $postId`;
        if (!post) return new Response('Not found', { status: 404 });
        return new Response(JSON.stringify(post), { headers: { 'content-type': 'application/json' } });
    };
    
    export const config = {
        runtime: 'edge',
        regions: ['iad1'], // specify the region nearest to your Neon DB
    };
  3. Test and deploy your application:
    • Install Vercel CLI globally: npm install -g vercel
    • Add your environment variable: npx vercel env add DATABASE_URL
    • Run your application locally: npx vercel dev
    • Deploy your application: npx vercel deploy

Handling Sessions and Transactions

When using the neon function, it can only handle one query at a time. However, you can use the transaction() function for multiple queries within a single, non-interactive transaction:

import neon from '@neondatabaseserverless';
const sql = neon(process.env.DATABASE_URL);

const showLatestN = 10;
const [posts, tags] = await sql.transaction([
    sql`SELECT * FROM posts ORDER BY posted_at DESC LIMIT $showLatestN`,
    sql`SELECT * FROM tags`,
]);

Connecting with Pool and Client

If you need session or interactive transaction support, use the Pool or Client constructors, which offer compatibility with node-postgres. Here’s a quick example:

import { Pool } from '@neondatabaseserverless';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

const client = await pool.connect();
try {
    await client.query('BEGIN');
    // Your SQL operations
    await client.query('COMMIT');
} catch (err) {
    await client.query('ROLLBACK');
    throw err;
} finally {
    client.release();
}

Troubleshooting Tips

  • If you encounter issues with connections, ensure that the WebSocket constructor is correctly set if your environment requires it.
  • Remember, in serverless environments, never create Pool or Client outside the request handler.
  • If you experience delayed responses, check if multiple requests are being made concurrently without closing previous connections.
  • For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Conclusion

With @neondatabaseserverless, you can leverage the power and speed of serverless PostgreSQL in your applications with ease. From installation to deployment, this guide provides a solid foundation to help you hit the ground running!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox