Connecting to databases
It is common for applications to store and retrieve data from databases. Denosupports connecting to many database management systems.
Deno supports multiple third-party modules that allow you to connect to SQL andNoSQL databases, including MySQL, PostgreSQL, MongoDB, SQLite, Firebase, andSupabase.
You can find helpful database connectivity modules onJSRand deno supports many npm packages with the use ofnpm specifiers.
SQLiteJump to heading
SQLite is a self-contained, serverless, zero-configuration, and transactionalSQL database engine. It is a popular choice for local storage in applications.
You can use multiple modules to connect to SQLite in Deno, including thebuilt-innode:sqlite
module and thesqlite module on JSR.
To use thesqlite module to connect to SQLite inyour Deno apps:
denoadd jsr:@db/sqlite
Then, import theDatabase
class from the module and create a new databaseinstance. You can then execute SQL queries against the database:
import{ Database}from"@db/sqlite";const db=newDatabase("test.db");const[version]= db.prepare("select sqlite_version()").value<[string]>()!;console.log(version);db.close();
This module depends on Deno FFI, so you need to run your script with the--allow-ffi
flag:
deno run --allow-ffi main.ts
MySQLJump to heading
You can use themysql npm module toconnect to MySQL databases. Install the module with the npm specifier:
denoadd npm:mysql
Then, import themysql
module and create a connection to your MySQL database:
import mysqlfrom"mysql";// Minimal connection config (edit as needed or use env vars)const connection= mysql.createConnection({ host: Deno.env.get("MYSQL_HOST")||"localhost", port:Number(Deno.env.get("MYSQL_PORT")||"3306"), user: Deno.env.get("MYSQL_USER")||"root", password: Deno.env.get("MYSQL_PASSWORD")||"", database: Deno.env.get("MYSQL_DATABASE")||"test",});connection.connect((err)=>{if(err){console.error("Connection error:", err);return;}console.log("Connected!"); connection.query("SELECT VERSION() AS version",(err, results)=>{if(err){console.error("Query error:", err);}else{console.log("MySQL version:", results[0].version);} connection.end();});});
PostgresJump to heading
PostgreSQL is a powerful, open source object-relational database system. You canuse multiple modules to connect to PostgreSQL in Deno, includingpg orpostgresjs.
Install the module with the npm specifier:
denoadd npm:pg
First, import theClient
class from thepg
module and create a new clientinstance. Then connect to the database passing an object with the connectiondetails:
import{ Client}from"pg";// Connection config (edit or use env vars)const client=newClient({ host: Deno.env.get("PGHOST")||"localhost", port:Number(Deno.env.get("PGPORT")||"5432"), user: Deno.env.get("PGUSER")||"postgres", password: Deno.env.get("PGPASSWORD")||"postgres", database: Deno.env.get("PGDATABASE")||"postgres",});asyncfunctionmain(){try{await client.connect();console.log("Connected!");const res=await client.query("SELECT version() AS version");console.log("Postgres version:", res.rows[0].version);}catch(err){console.error("Connection/query error:", err);}finally{await client.end();}}main();
MongoDBJump to heading
MongoDB is a popular NoSQL database that stores data in flexible, JSON-likedocuments. You can use the officialMongoDB Node.js driver to connect toMongoDB, or theMongo db driver from JSR.
Import the MongoDB driver, set up connection configuration then connect to aMongoDB instance:
import{ MongoClient}from"mongodb";const url="mongodb://mongo:mongo@localhost:27017";// username:password@host:portconst client=newMongoClient(url);const dbName="myProject";await client.connect();console.log("Connected successfully to server");const db= client.db(dbName);const collection= db.collection("documents");const insertResult=await collection.insertMany([{ a:1},{ a:2}]);console.log("Inserted documents =>", insertResult);await client.close();
FirebaseJump to heading
Firebase is a platform developed by Google for creating mobile and webapplications. It provides a variety of services, including a NoSQL database,authentication, and hosting.
To connect to Firebase, you can use the official npm modules provided byFirebase, you will need to update yourdeno.json
to tell deno to use anode_modules
directory, and allow scripts when installing:
"nodeModulesDir": auto
denoadd npm:firebase --allow-scripts
Then import the necessary functions from the Firebase modules and initializeyour app and services:
import{ initializeApp}from"firebase/app";import{ doc, getDoc, getFirestore, setDoc}from"firebase/firestore";// Replace with your Firebase config (get from Firebase Console)const firebaseConfig={apiKey:"YOUR_API_KEY",authDomain:"YOUR_PROJECT_ID.firebaseapp.com",projectId:"YOUR_PROJECT_ID",storageBucket:"YOUR_PROJECT_ID.appspot.com",messagingSenderId:"YOUR_MESSAGING_SENDER_ID",appId:"YOUR_APP_ID",};// Initialize Firebaseconst app=initializeApp(firebaseConfig);const db=getFirestore(app);// Demo: write and read a documentasyncfunctiondemo(){const ref=doc(db,"demo","testdoc");awaitsetDoc(ref,{hello:"world",time: Date.now()});const snap=awaitgetDoc(ref); console.log("Document data:", snap.data());}demo().catch(console.error);
SupabaseJump to heading
Supabase is an open-source Firebase alternative that provides a suite of toolsand services to help you build and scale applications. It offers a hostedPostgreSQL database, authentication, real-time subscriptions, and storage.
To connect to Supabase, you can use the@supabase/supabase-js npmmodule.
First, install the module with the npm specifier:
denoadd npm:@supabase/supabase-js --allow-scripts
Then, import thecreateClient
function from the module and create a newSupabase client instance. You will need your Supabase project URL and an APIkey, which you can find in your Supabase project settings:
import{ createClient}from"@supabase/supabase-js";const url= Deno.env.get("SUPABASE_URL")??"https://YOUR-PROJECT.ref.supabase.co";const key= Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")??"";const supabase=createClient(url, key);asyncfunctionmain(){const{ data, error}=await supabase.from("demo").insert({ message:`Hello @${newDate().toISOString()}`}).select().maybeSingle();if(error){console.error("Insert failed:", error.message);console.error("Hint: If this is an RLS error, either disable RLS on 'demo' or add a policy allowing anon inserts.",);return;}console.log("Inserted row:", data);}if(import.meta.main)main();
ORMsJump to heading
Object-Relational Mappings (ORM) define your data models as classes that you canpersist to a database. You can read and write data in your database throughinstances of these classes.
Deno supports multiple ORMs, including Prisma, Drizzle, and Kysely.
🦕 Now you can connect your Deno project to a database you'll be able to workwith persistent data, perform CRUD operations and start building more complexapplications.