API reference
Complete API documentation for @kesha-antonov/react-native-background-downloader.
Named Exports
The library exports the following functions and objects:
import {
setConfig,
createDownloadTask,
createUploadTask,
getExistingDownloadTasks,
getExistingUploadTasks,
completeHandler,
directories
} from '@kesha-antonov/react-native-background-downloader'
createDownloadTask(options)
Download a file to destination.
Options
| Property | Type | Required | Platforms | Description |
|---|---|---|---|---|
id | String | ✅ | All | A unique ID to provide for this download. This ID will help to identify the download task when the app re-launches |
url | String | ✅ | All | URL to file you want to download |
destination | String | ✅ | All | Where to copy the file to once the download is done. The 'file://' prefix will be automatically removed if present |
metadata | Record<string, unknown> | All | Custom data to be preserved across app restarts. Will be serialized to JSON | |
headers | Record<string, string | null> | All | Custom headers to add to the download request. These are merged with the headers given in setConfig({ headers: { ... } }). Headers with null values will be removed | |
maxRedirects | Number | Android | Maximum number of redirects to follow before passing URL to DownloadManager. If not specified or 0, no redirect resolution is performed. Helps avoid ERROR_TOO_MANY_REDIRECTS for URLs with many redirects (e.g., podcast URLs) | |
isAllowedOverRoaming | Boolean | Android | Whether this download may proceed over a roaming connection. By default, roaming is allowed | |
isAllowedOverMetered | Boolean | All | Whether this download may proceed over a metered (cellular) network connection. Defaults to the global allowsCellularAccess |
Returns
DownloadTask - The download task to control and monitor this download. Call task.start() to begin the download.
getExistingDownloadTasks()
Checks for downloads that ran in background while your app was terminated.
Recommended to run at the init stage of the app.
Returns
Promise<DownloadTask[]> - A promise that resolves to an array of tasks that were running in the background so you can re-attach callbacks to them.
createUploadTask(options)
Upload a file to a server.
Options
| Property | Type | Required | Platforms | Description |
|---|---|---|---|---|
id | String | ✅ | All | A unique ID to provide for this upload. This ID will help to identify the upload task when the app re-launches |
url | String | ✅ | All | URL to upload the file to. Not needed with partUrls |
source | String | ✅ | All | Path to the local file to upload. The 'file://' prefix will be automatically removed if present |
method | 'POST' | 'PUT' | 'PATCH' | All | HTTP method for upload. Default is 'POST', or 'PUT' with partUrls | |
metadata | Record<string, unknown> | All | Custom data to be preserved across app restarts. Will be serialized to JSON | |
headers | Record<string, string | null> | All | Custom headers to add to the upload request. These are merged with the headers given in setConfig({ headers: { ... } }). Headers with null values will be removed | |
fieldName | String | All | Name of the multipart form field for the file. Default is 'file' | |
mimeType | String | All | MIME type of the file being uploaded. Default is inferred from file extension | |
parameters | Record<string, string> | All | Additional form parameters to send with the upload | |
partUrls | String[] | All | Upload the file in parts, one URL per part (e.g. S3 multipart upload with a presigned UploadPart URL each). Part i is sent as the raw body to partUrls[i]; can't be combined with fieldName or parameters. See Uploading in parts | |
partSize | Number | All | Bytes per part with partUrls, the last part taking what's left. Defaults to Math.ceil(fileSize / partUrls.length). The upload fails if the parts don't cover the file exactly | |
isAllowedOverRoaming | Boolean | Android | Whether this upload may proceed over a roaming connection. By default, roaming is allowed | |
isAllowedOverMetered | Boolean | All | Whether this upload may proceed over a metered (cellular) network connection. Defaults to the global allowsCellularAccess |
Returns
UploadTask - The upload task to control and monitor this upload. Call task.start() to begin the upload.
Uploading in parts
With partUrls, one task uploads the file across the URLs: progress is the sum of the parts against the file size, and done fires once every part was accepted, with each part's response (including its ETag header) in parts. Any part the server doesn't accept (not 2xx) fails the whole upload with that status as errorCode.
- Android sends the parts one after another, each read straight from its byte range of the file. Accepted parts are saved, so a paused or restarted upload continues with the first part that isn't in yet.
- iOS background sessions upload only from a file, so each part is copied into a temporary file (needing up to the file's size in free space) and uploaded as its own background task, several at a time. Each copy is deleted as soon as its part is accepted.
If an upload finishes while the app isn't running (iOS), its response, parts included, is returned by getExistingUploadTasks() as a DONE task.
getExistingUploadTasks()
Checks for uploads that ran in background while your app was terminated.
Recommended to run at the init stage of the app.
Returns
Promise<UploadTask[]> - A promise that resolves to an array of upload tasks that were running in the background so you can re-attach callbacks to them. On iOS it also returns, once, uploads that finished while the app wasn't running: they have state: 'DONE' and carry responseCode, responseBody, responseHeaders and parts.
setConfig(config)
Sets global configuration for the downloader.
Config Options
| Name | Type | Description |
|---|---|---|
headers | Record<string, string | null> | Optional headers to use in all future downloads. Headers with null values will be removed |
progressInterval | Number | Interval in milliseconds for download progress updates. Must be >= 250. Default is 1000 |
progressMinBytes | Number | Minimum number of bytes that must be downloaded before a progress event is emitted. When set to 0, only the percentage threshold (1% change) triggers progress updates. Default is 1048576 (1MB) |
isLogsEnabled | Boolean | Enables/disables verbose debug logs in native code (iOS and Android). Works in both debug and release builds. Default is false |
logCallback | (log: { message: string, taskId?: string }) => void | Optional callback function to receive native debug logs in JavaScript. Only called when isLogsEnabled is true |
maxParallelDownloads | Number | Maximum number of downloads transferring at once. Must be >= 1. Default is 4. On iOS this is the session's maximum simultaneous connections per host. On Android it caps the library's own downloader (the mechanism used on Android 16+, and whenever DownloadManager or a UIDT job can't take the download); downloads running through DownloadManager or the JobScheduler are queued by those instead |
allowsCellularAccess | Boolean | Controls whether downloads are allowed over cellular (metered) connections. When set to false, downloads and uploads will only occur over WiFi. Default is true. It's the default for each task's isAllowedOverMetered, so it applies to tasks created after the call; a task can override it either way |
showNotificationsEnabled | Boolean | Android only. Show full download notifications. When false, creates minimal silent notifications (UIDT jobs on Android 14+ require a notification, but it will be barely visible). Default is false |
showCompletionNotification | Boolean | Android 14+ only. Post a "download complete" notification when a download finishes; tapping it opens the saved file. Requires showNotificationsEnabled, and is skipped in summaryOnly grouping mode. Default is false |
showCancelAction | Boolean | Android 14+ only. Add a Cancel button to the download notification. Tapping it stops the download and fires the task's .error() handler with errorCode = -1, so only enable it if your app handles that. Requires showNotificationsEnabled. Default is false |
notificationsGrouping | Object | Android only. Configuration for notification grouping. See below for details |
notificationsGrouping Options (Android only):
| Name | Type | Description |
|---|---|---|
enabled | Boolean | Enable notification grouping. Default is false |
texts | Object | Customizable notification texts. All fields are optional - defaults are used for any omitted fields |
notificationsGrouping.texts — Customizable Notification Strings:
| Key | Default | Placeholders | Description |
|---|---|---|---|
downloadTitle | 'Download' | — | Title shown in individual download notifications |
downloadStarting | 'Starting download...' | — | Notification text when a download begins |
downloadProgress | 'Downloading... {progress}%' | {progress} — current percentage (0-100) | Text shown while download is in progress |
downloadPaused | 'Paused' | — | Text shown when download is paused |
downloadFinished | 'Download complete' | — | Text shown when download completes |
downloadCancel | 'Cancel' | — | Label of the Cancel action on the notification (Android 14+, only when showCancelAction is enabled) |
groupTitle | 'Downloads' | — | Title for the group summary notification (when multiple downloads are active) |
groupText | '{count} download(s) in progress' | {count} — number of active downloads | Summary text showing how many downloads are running |
Example
import { setConfig } from '@kesha-antonov/react-native-background-downloader'
// Configure parallel downloads and cellular access
setConfig({
maxParallelDownloads: 8, // max downloads transferring at once
allowsCellularAccess: false, // Only download over WiFi
})
// Enable verbose logging with callback
setConfig({
isLogsEnabled: true,
logCallback: (log) => {
console.log('[BackgroundDownloader]', log.message, log.taskId ? `(${log.taskId})` : '')
}
})
// Or just enable native console logging without JS callback
setConfig({
isLogsEnabled: true
})
// Android: Enable notifications with custom texts
setConfig({
showNotificationsEnabled: true,
// Android 14+ extras, both opt-in
showCompletionNotification: true,
showCancelAction: true,
notificationsGrouping: {
enabled: true,
texts: {
downloadTitle: 'My App Download',
downloadStarting: 'Preparing...',
downloadProgress: '{progress}% complete',
downloadPaused: 'Download paused',
downloadFinished: 'Done!',
downloadCancel: 'Stop',
groupTitle: 'Downloads',
groupText: '{count} files downloading',
},
},
})
completeHandler(jobId: string)
Finishes download job and informs OS that app can be closed in background if needed. After finishing download in background you have some time to process your JS logic and finish the job.
Parameters
jobId(String) - The ID of the download task to complete
Note: Call it for every task, in both the
doneand theerrorcallback, once you've processed the result. On iOS, after a background launch the library tells the OS it's finished when iOS has delivered all of the launch's events and every task that finished in it has been passed tocompleteHandler, or after 25 seconds at the latest. On Android it does nothing.
DownloadTask
A class representing a download task created by createDownloadTask().
Note: You must call
task.start()to begin the download after setting up event handlers.
Members
| Name | Type | Description |
|---|---|---|
id | String | The id you gave the task when calling createDownloadTask |
metadata | Record<string, unknown> | The metadata you gave the task when calling createDownloadTask |
state | 'PENDING' | 'DOWNLOADING' | 'PAUSED' | 'DONE' | 'FAILED' | 'STOPPED' | Current state of the download task |
bytesDownloaded | Number | The number of bytes currently written by the task |
bytesTotal | Number | The number bytes expected to be written by this task or more plainly, the file size being downloaded. Note: This value will be -1 if the server does not provide a Content-Length header |
downloadParams | DownloadParams | The download parameters set for this task |
Callback Methods
Use these methods to stay updated on what's happening with the task. All callback methods return the current instance of the DownloadTask for chaining.
| Function | Callback Arguments | Description |
|---|---|---|
begin | { expectedBytes: number, headers: Record<string, string | null> } | Called once, when the first byte is received; not again on resume. 💡 This is a good place to check if the device has enough storage space for this download |
progress | { bytesDownloaded: number, bytesTotal: number } | Called based on progressInterval (default: every 1000ms) so you can update your progress bar accordingly. Note: bytesTotal will be -1 if the server does not provide a Content-Length header |
done | { location: string, bytesDownloaded: number, bytesTotal: number } | Called when the download is done, the file is at the destination you've set. location is the final file path. Note: bytesTotal will be -1 if the server did not provide a Content-Length header |
error | { error: string, errorCode: number } | Called when the download stops due to an error. A download the network cuts off (a stall, a dropped connection, a timeout) first continues from where it stopped, a few times; error fires only if that doesn't get data through |
Methods
setDownloadParams(params): Promise<boolean>
Updates the download parameters. If the task is paused, this will also update headers in the native layer, allowing you to refresh authentication tokens before resuming.
Parameters:
params(DownloadParams) - The new download parameters. Same structure as options passed tocreateDownloadTask()
Returns: Promise<boolean> - Resolves to true if native headers were updated (task was paused), false otherwise.
Example:
// Update auth token on a paused download before resuming
if (task.state === 'PAUSED') {
const updated = await task.setDownloadParams({
...task.downloadParams,
headers: {
...task.downloadParams?.headers,
Authorization: 'Bearer new-refreshed-token'
}
})
console.log('Headers updated:', updated) // true
await task.resume()
}
Note: When headers are updated on a paused task:
- iOS: The download resumes using a fresh request with HTTP Range header and the new headers
- Android: Both in-memory headers and persisted paused download state are updated
pause(): Promise<void>
Pauses the download. Returns a promise that resolves when the pause operation is complete.
Note: On Android, pause/resume is implemented using HTTP Range headers, which requires server support. The download progress is saved and resumed from where it left off.
resume(): Promise<void>
Resumes a paused download. Returns a promise that resolves when the resume operation is complete.
Note: On Android, this uses HTTP Range headers to resume from the last downloaded byte position. If the server doesn't support range requests, the download will restart from the beginning.
stop(): Promise<void>
Stops the download for good and removes the file that was written so far. Returns a promise that resolves when the stop operation is complete.
start(): void
Starts the download.
UploadTask
A class representing an upload task created by createUploadTask().
Note: You must call
task.start()to begin the upload after setting up event handlers.
Members
| Name | Type | Description |
|---|---|---|
id | String | The id you gave the task when calling createUploadTask |
metadata | Record<string, unknown> | The metadata you gave the task when calling createUploadTask |
state | 'PENDING' | 'UPLOADING' | 'PAUSED' | 'DONE' | 'FAILED' | 'STOPPED' | Current state of the upload task |
bytesUploaded | Number | The number of bytes currently uploaded by the task |
bytesTotal | Number | The total number bytes to be uploaded by this task |
uploadParams | UploadParams | The upload parameters set for this task |
responseCode, responseBody, responseHeaders, parts | Set once the upload is done; see done below |
Callback Methods
| Function | Callback Arguments | Description |
|---|---|---|
begin | { expectedBytes: number } | Called once, when the upload starts; not again on resume |
progress | { bytesUploaded: number, bytesTotal: number } | Called based on progressInterval (default: every 1000ms) so you can update your progress bar accordingly |
done | { responseCode: number, responseBody: string, responseHeaders: Record<string, string>, parts?: UploadPartResult[], bytesUploaded: number, bytesTotal: number } | Called when the upload is done. responseHeaders has lowercased names (responseHeaders.etag). With partUrls, parts lists each part in order as { partNumber, responseCode, responseBody, responseHeaders, bytes }, and the other response fields are the last part's |
error | { error: string, errorCode: number } | Called when the upload stops due to an error |
Methods
pause(): Promise<void>- Pauses the upload (platform support may vary)resume(): Promise<void>- Resumes a paused uploadstop(): Promise<void>- Stops the upload and removes temporary datastart(): void- Starts the upload
Constants
directories
documents
An absolute path to the app's documents directory. It is recommended that you use this path as the target of downloaded files.
import { directories } from '@kesha-antonov/react-native-background-downloader'
const destination = `${directories.documents}/my-file.zip`