'Hooks.js running the db connection and results twice in sveltekit

I'm using sveltekit and trying to understand all the new features added after retiring Sapper. One of those new features is hooks.js which runs on the server and not accessible to the frontend. It makes dealing with db safe. So I created a connection to my mongodb to retrieve user's data before I use the db results in my getSession function. It works but I noticed that it access my database TWICE. Here is my hooks.js code:

import * as cookie from 'cookie';
import { connectToDatabase } from '$lib/mongodb.js';    

export const handle = async ({event, resolve})=>{    

const dbConnection = await connectToDatabase();
const db = dbConnection.db;    

const userinfo = await db.collection('users').findOne({ username: "a" });
console.log("db user is :" , userinfo) //username : John

const response = await resolve(event)

response.headers.set(
            'set-cookie', cookie.serialize("cookiewithjwt", "sticksafterrefresh")
    )    
return  response

} 

export const getSession = (event)=>{
    return {
        user : {
            name : "whatever"
        }
    }    
}

The console.log you see here returns the user data twice. One as soon as I fire up my app at localhost:3000 with npm run dev and then less than a second, it prints another console log with the same information

  db user is : John 

a second later without clicking on anything a second console.log prints

db user is : John

So my understanding from the sveltekit doc is that hooks.js runs every time SvelteKit receives a request. I removed all prerender and prefetch from my code. I made sure I only have the index.svelte in my app but still it prints twice. My connection code I copied from an online post has the following:

/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/

Here is my connection code:

import { MongoClient } from 'mongodb';
const mongoURI ="mongodb+srv://xxx:[email protected]/xxxxdb?retryWrites=true&w=majority";
const mongoDB = "xxxxdb"

export const MONGODB_URI = mongoURI;
export const MONGODB_DB = mongoDB;

if (!MONGODB_URI) {
    throw new Error('Please define the mongoURI property inside config/default.json');
}

if (!MONGODB_DB) {
    throw new Error('Please define the mongoDB property inside config/default.json');
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */

let cached = global.mongo;

if (!cached) {
    cached = global.mongo = { conn: null, promise: null };
}

export const connectToDatabase = async() => {
    if (cached.conn) {
        return cached.conn;
    }

if (!cached.promise) {
    const opts = {
        useNewUrlParser: true,
        useUnifiedTopology: true
    };

    cached.promise = MongoClient.connect(MONGODB_URI).then((client) => {
        return {
            client,
            db: client.db(MONGODB_DB)
        };
    });
}
cached.conn = await cached.promise;
return cached.conn;

So my question is : is hooks.js runs twice all the time, one time on the server and one time on the front? If not, then why the hooks.js running/printing twice the db results in my case?

Anyone?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source