---
title: Avoid hardcoding credentials in source code
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid hardcoding credentials in source code
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Avoid hardcoding credentials in source code

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `dart-security/hardcoded-credentials`

**Language:** Dart

**Severity:** Error

**Category:** Security

**CWE**: [798](https://cwe.mitre.org/data/definitions/798.html)

## Description{% #description %}

Hardcoding credentials such as passwords, API keys, tokens, or secrets as string literals exposes them to anyone with access to the source code or the compiled application. Secrets embedded in code are trivially extracted from compiled apps and leak through version control history, where they remain even after being removed.

Load credentials at runtime from environment variables or a secrets manager instead of writing them directly into the code.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```dart
class Service {
  final password = 'hunter2';
  var apiKey = 'AKIAIOSFODNN7EXAMPLE';
  String secret = 'xyz';
}

void sendCredentials() {
  connect(password: 'hunter2');
  buildClient(apiKey: 'sk-test-1234567890');
}

void connect({String? password}) {}
void buildClient({String? apiKey}) {}
```

## Compliant Code Examples{% #compliant-code-examples %}

```dart
import 'dart:io';

class Config {
  final String password = Platform.environment['DB_PASSWORD']!;
  final apiKey = const String.fromEnvironment('API_KEY');
  final token = readSecret();
  final secret = otherVar;
}

String readSecret() => Platform.environment['SECRET']!;

void nonCredentialNames() {
  final username = 'admin';
  final name = 'bob';
  final displayLabel = 'Sign in';
  final password = '';
  final apiKey = "";
}

void interpolated(String base) {
  final password = '$base-suffix';
  final token = "Bearer ${base}";
  connect(secret: 'prefix_$base');
}

void connect({String? secret}) {}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 