DEV Community

Cover image for How to connect to a MongoDB database in Sveltekit
Abdulmumin yaqeen
Abdulmumin yaqeen

Posted on • Edited on • Originally published at yaqeen.me

8 2 2

How to connect to a MongoDB database in Sveltekit

While a database like Mongo is not the go-to choice for a lot of devs, It has gained quite alot of honest users and a thriving community. If you’re here, you are likely part of this community.

MongoDB is a document-oriented database, which means it allows for flexible and dynamic schema design. This flexibility is particularly beneficial in scenarios where the data structure evolves over time.

In this article, we will take a look at a non-obvious trick that many Sveltekit users have used to securely connect to their Mongo database.

How?

We will be utilizing the Sveltekit hook for this, as it allows us to create the connection only once, before starting the server.

Sounds confusing? here is an example.

1. Create our MongoDB client

mongo.ts

import { MONGO_URL } from '$env/static/private';
import { MongoClient } from 'mongodb';

const client = new MongoClient(MONGO_URL);

// connect to the database
export async function connect(): Promise<void> {
    await client.connect();
}
Enter fullscreen mode Exit fullscreen mode

If you’re not familiar with Sveltekit $env management — Environment variables in process.env are also available via $env/static/private.

2. Execute the connection in Sveltekit hook.

hooks.server.ts

import { connect } from '$db/mongo';

// Connect to MongoDB before starting the server
connect()
    .then((): void => {
        console.log('MongoDB started');
    })
    .catch((e) => {
        console.log('MongoDB failed to start');
        console.log(e);
    });
Enter fullscreen mode Exit fullscreen mode

This will allow the database connection to happen only once, and that too before starting the app. Most of us are familiar with using the hook with the handle function that can intercept requests and is used to secure routes.

But that only happens to stuff in the handle functions, every other thing invoked outside of the handle function will be executed only once before the app starts.

There you have it, how to connect your MongoDB in Sveltekit. Good luck playing around with NoSQL 😅

Peace ✌️

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs