---
description: >-
  It's time to actually remove that data from the codebase and use it through
  environment variables.
---

# Using the variables

Now, let's go back to the <mark style="color:blue;">`DatabaseModule`</mark> and connect to the database in a different manner: **asynchronously** and using a **factory**. This means that, instead of already receiving the credentials directly in the code, it will await the environment variables to load in order to use them. Now we can also use just the URL, and have the following result:

```typescript
TypeOrmModule.forRootAsync({
  useFactory: () => ({
    type: 'postgres',
    url: process.env.DATABASE_URL,
    autoLoadEntities: true,
  }),
}),
```

Also, back in the file <mark style="color:purple;">docker-compose.yml</mark>, let's use the <mark style="color:blue;">`password`</mark> from the <mark style="color:purple;">.env</mark> too.

```yaml
POSTGRES_PASSWORD: ${DATABASE_PASSWORD}
```

And do the same with the <mark style="color:blue;">`port`</mark>.

```yaml
ports:
  - ${DATABASE_PORT}:5432
```

In the <mark style="color:purple;">data-source</mark> file, unfortunately we'll need to use the packages **dotenv** and **dotenv-expand** directly, as it has no integration with Nest and, because of that, the <mark style="color:blue;">`ConfigModule`</mark> can't be used here. We'll also need to write the imports manually because these packages are sub-dependencies, and as such will not benefit from code completion.

```typescript
import * as dotenv from 'dotenv';
import * as dotenvExpand from 'dotenv-expand';

dotenvExpand.expand(dotenv.config());

export default new DataSource({
  // ...
  url: process.env.DATABASE_URL,
  // ...
});
```

<mark style="color:green;">**Commit**</mark> - Using environment variables
