Initializing and destroying database connections

Hi coders.
I want to use typeorm in a serverless app in AWS.

I create a new connection in each handler and I also destroy the connection in the same handler.

The problem is that I sometimes get this message:
CannotConnectAlreadyConnectedError: Cannot create a “default” connection because connection to the database already established

Are there startup and shutdown callbacks I can use?
Is there another way to handle this?
Did I get something obvious wrong?

It looks to me like serverless functions sometimes have state from other calls and sometimes are completely separate instances.

Code for reference:

import express, { Request, Response } from 'express';
import { AppDataSource } from "../data-source";
import { Statistic } from "../entity/Statistic";

export const statisticsRoute = express.Router();"/v1/statistics", async (req : Request, res : Response) => {
    let result = { status: 1 } as any;
    let data = req.body;
    try {
        await AppDataSource.initialize();
        let stats = new Statistic();
        stats.sessionId = data.sessionId;
        // …

    } catch (e) {
        console.error("Error in statistics call: ", e);
        res.statusCode = 500;
        result = { status: 0, message: "API error." };

    try {
        await AppDataSource.destroy();
    } catch (e) {
        console.error("Error in closing db function: ", e);

    res.setHeader("content-type", "application/json");

Hi johanmattsson,

A few weeks ago I had the same problem which I wasn’t able to create a new connection even though I destroyed the connection I used.

I had to create a new connection as default using connection manager, then getConnection / createConnection conditionally.

If you are going to take this route, this posting will be helpful.
Wiring up TypeORM with Serverless | by Karim Varela | Safara Engineering | Medium