Code Icon

Build an app / Next.js + MongoDB Driver

How to connect a Next.js app to SingleStore using the MongoDB driver

on-this-guideOn this guide

This guide walks you through the steps to connect a Next.js application to a SingleStore database using the MongoDB driver. You’ll start by setting up a SingleStore deployment and workspace, then create a database and retrieve your connection credentials. Finally, you’ll configure your Next.js project by installing the mongodb package, loading environment variables, and establishing a connection to handle queries against your SingleStore instance. By the end, you’ll have a working example that you can use in your application.

prerequisitesPrerequisites

  • SingleStore account
  • Node.js

Don’t have a SingleStore account yet?

Sign up nowArrow Up Right Icon

create-deploymentCreate deployment

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Create NewDeployment.

3. In the Create Workspace form, follow the on‑screen instructions to complete the form.

4. Enable SingleStore Kai.

5. Click Create Workspace.

6. Wait for the workspace to finish deploying.

create-workspaceCreate workspace

Note: If the required workspace already exists in the target deployment, you can skip this step.

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment where you want to create a workspace.

4. In the left‑hand pane, click + Create Workspace.

5. Enable SingleStore Kai.

6. Follow the on‑screen instructions to complete the form.

7. Click Create Workspace.

8. Wait for the workspace to finish deploying.

create-databaseCreate database

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment where you want to create a database.

4. In the right‑hand pane, click + Create Database.

5. In the Create Database form, enter a new database name and select the workspace to attach it to.

6. Click Create Database.

retrieve-database-credentialsRetrieve database credentials

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment that contains your database.

4. From the workspaces list, select the workspace to which your database is attached.

5. In the selected workspace, click Connect.

6. In the Connect dropdown, choose MongoDB Client.

7. In the MongoDB Client tab, copy the connection string.

If you don’t know the password, click Reset Password, then copy the new password.

prepare-environmentPrepare environment

1. Create a .env file in the root of your project.

2. In this file, define your connection string and database name by adding DB_URL and DB_NAME variables, for example:

1

DB_URL="mongodb://<USER>:<PASSWORD>@<HOST>:<PORT>/?authMechanism=PLAIN&tls=true&loadBalanced=true"

2

DB_NAME="<DATABASE_NAME>"

If you don’t know your connection string, see the Retrieve database credentials section above.

3. Now, in a terminal pointing to the root directory of your project, install the mongodb NPM package by running the following command:

1

npm i mongodb

establish-database-connectionEstablish database connection

In the root directory of your project, create a db.js file with the following content to define a helper function that establishes a database connection:

1

import { MongoClient } from "mongodb";

2

3

export async function connectDB() {

4

const client = new MongoClient(process.env.DB_URL);

5

await client.connect();

6

const db = client.db(process.env.DB_NAME);

7

8

return db;

9

}

query-databaseQuery database

Once you’ve added the above code, let’s test to make sure that the connection is working as anticipated. 


Next.js route handlers let you create custom request handlers for a given route using the Web Request and Response APIs. Follow these steps to implement an example app:

1. Create a route.js file at ./app/api/users with the following content to handle requests for retrieving and creating users:

1

import { connectDB } from "../../../db";

2

3

export async function GET() {

4

const db = await connectDB();

5

const rows = await db.collection("users").find().toArray();

6

return Response.json(rows);

7

}

8

9

export async function POST(request) {

10

const { name } = await request.json();

11

const db = await connectDB();

12

const result = await db.collection("users").insertOne({ name });

13

return Response.json(result);

14

}

2. Create a route.js file at ./app/api/users/[id] with the following content to handle requests for retrieving a user by ID, updating a user's name, and deleting a user:

1

import { connectDB } from "../../../../db";

2

import { ObjectId } from "mongodb";

3

4

export async function GET(request, { params }) {

5

const { id } = await params;

6

const db = await connectDB();

7

const row = await db.collection("users").findOne({ _id: new ObjectId(id) });

8

return Response.json(row);

9

}

10

11

export async function PUT(request, { params }) {

12

const { id } = await params;

13

const { name } = await request.json();

14

const db = await connectDB();

15

console.log({ id, name });

16

const result = await db.collection("users").updateOne({ _id: new ObjectId(id) }, { $set: { name } });

17

console.log(result);

18

return Response.json(result);

19

}

20

21

export async function DELETE(request, { params }) {

22

const { id } = await params;

23

const db = await connectDB();

24

const result = await db.collection("users").deleteOne({ _id: new ObjectId(id) });

25

return Response.json(result);

26

}

3. Create a <DBTest /> client component in ./components/DBTest.jsx with the following content:

1

"use client";

2

3

import { useCallback, useEffect, useState } from "react";

4

5

export function DBTest() {

6

const [users, setUsers] = useState([]);

7

const [nameValue, setNameValue] = useState("");

8

9

const fetchUsers = useCallback(async () => {

10

const response = await fetch("/api/users");

11

const data = await response.json();

12

setUsers(data);

13

}, []);

14

15

const createUser = async () => {

16

await fetch("/api/users", {

17

method: "POST",

18

body: JSON.stringify({ name: nameValue }),

19

});

20

21

await fetchUsers();

22

};

23

24

const updateUser = async (user) => {

25

const newName = `${user.name.split(" - ")[0]} - ${new Date().toISOString()}`;

26

27

await fetch(`/api/users/${user._id}`, {

28

method: "PUT",

29

body: JSON.stringify({ name: newName }),

30

});

31

32

await fetchUsers();

33

};

34

35

const deleteUser = async (id) => {

36

await fetch(`/api/users/${id}`, { method: "DELETE" });

37

await fetchUsers();

38

};

39

40

const handleFormSubmit = async (event) => {

41

event.preventDefault();

42

await createUser();

43

setNameValue("");

44

};

45

46

useEffect(() => {

47

fetchUsers();

48

}, [fetchUsers]);

49

50

return (

51

<section>

52

<h2>Users</h2>

53

54

<form

55

className="mt-4"

56

onSubmit={handleFormSubmit}

57

>

58

<input

59

type="text"

60

name="name"

61

placeholder="e.g. John Doe"

62

className="bg-black border px-2 p-1"

63

value={nameValue}

64

onChange={(event) => setNameValue(event.target.value)}

65

/>

66

<button

67

type="submit"

68

className="border px-2 ml-2 py-1"

69

>

70

Add

71

</button>

72

</form>

73

74

<ul className="border p-4 mt-4 flex flex-col gap-2">

75

{users.map((user) => (

76

<li key={user._id}>

77

<p>

78

{user._id} - {user.name}

79

</p>

80

<button onClick={() => updateUser(user)}>Update</button>

81

<button

82

onClick={() => deleteUser(user._id)}

83

className="ml-2"

84

>

85

Delete

86

</button>

87

</li>

88

))}

89

</ul>

90

</section>

91

);

92

}

4. Add the following code at ./app/page.js:

1

import { DBTest } from "../components/DBTest";

2

3

export default function Home() {

4

return (

5

<main className="p-4">

6

<DBTest />

7

</main>

8

);

9

}

5. Build the project by running:

1

npm run build

6. Start the project by running:

1

npm run start

7. Finally, open http://localhost:3000 in your browser to test the application.

error-handling-and-troubleshootingError handling and troubleshooting

auth-failedAUTH_FAILED

If you receive an AUTH_FAILED exception when trying to establish a connection to database, try the following steps to remedy the issue: