LoopBack 4 Todo Application Tutorial - Add a Datasource
Page Contents


Datasources are LoopBack’s way of connecting to various sources of data, such as databases, APIs, message queues and more. In LoopBack 4, datasources can be represented as strongly-typed objects and freely made available for injection throughout the application. Typically, in LoopBack 4, datasources are used in conjunction with Repositories to provide access to data.

Since our Todo API will need to persist instances of Todo items, we’ll need to create a datasource definition to make this possible.

Building a Datasource

Create a new folder in the root directory of the project called config, and then inside that folder, create a datasources.json file. For the purposes of this tutorial, we’ll be using the memory connector provided with the Juggler.


  "name": "db",
  "connector": "memory"

Inside the src/datasources directory create a new file called db.datasource.ts. This file will create a strongly-typed export of our datasource using the DataSourceConstructor, which we can consume in our application via injection.


import * as path from 'path';
import {DataSourceConstructor, juggler} from '@loopback/repository';

const dsConfigPath = path.resolve('config', 'datasources.json');
const config = require(dsConfigPath);
export const db = new DataSourceConstructor(config);

Once you’re ready, we’ll move onto adding a repository for the datasource.

Previous step: Add your Todo model

Next step: Add a repository