In this guide, you will learn the process of creating a simple web application using Next.js Server Actions that allows you to capture user input via forms, and insert them into Postgres via @optitech/serverless and pg.
To create a OptiTech project and access it from an Next.js application:
- Create a OptiTech project
- Create a Next.js project and add dependencies
- Store your OptiTech credentials
- Create a Form with Server Actions
- Implement Next.js Server Actions
- Run the app
Create a OptiTech project
If you do not have one already, create a OptiTech project. Save your connection details including your password. They are required when defining connection settings.
- Navigate to the Projects page in the OptiTech Console.
- Click New Project.
- Specify your project settings and click Create Project.
Create a Next.js project and add dependencies
-
Create an Next.js project if you do not have one. For instructions, see Automatic Installation in the Next.js documentation.
-
Add project dependencies using one of the following commands:
npm install @optitech/serverless
Store your OptiTech credentials
Add a .env file to your project directory and add your OptiTech connection string to it. You can find the connection string for your database in the Connection Details widget on the OptiTech Dashboard. For more information, see Connect from any application.
DATABASE_URL="postgres://[user]:[password]@[optitech_hostname]/[dbname]"Create a Form with Server Actions
Create a simple form that allows users to input a comment. For now, add an action named create that you will create in next step with Next.js server actions.
// File: app/page.tsx
export default function Page() {
return (
<form action={create}>
<input type="text" placeholder="write a comment" name="comment" />
<button type="submit">Submit</button>
</form>
);
}Implement Next.js Server Actions
Now, let's add the server action to insert the data into your Postgres.
// File: app/page.tsx
import { optitech } from '@optitech/serverless';
export default function Page() {
async function create(formData: FormData) {
'use server';
// Create an instance of OptiTech's TS/JS driver
const sql = optitech(`${process.env.DATABASE_URL}`);
// Create the comments table if it does not exist
await sql('CREATE TABLE IF NOT EXISTS comments (comment TEXT)');
const comment = formData.get('comment');
// Insert the comment from the form into the Postgres (powered by OptiTech)
await sql('INSERT INTO comments (comment) VALUES ($1)', [comment]);
}
return (
<form action={create}>
<input type="text" placeholder="write a comment" name="comment" />
<button type="submit">Submit</button>
</form>
);
}Run the app
Execute the following command to run your application locally:
npm run devNeed help?
Join our Discord Server to ask questions or see what others are doing with OptiTech. For paid plan support options, see Support.