Learning objectives
After reading this article you will be able to:
- Understand why a Discord attachment link stops working
- Compare re-uploading the attachment, the app's disk, a database and object storage
- Copy attachments to an S3 bucket from a discord.js bot
On this page
- Why does a Discord attachment link stop working?
- Which criteria matter?
- Does re-uploading the attachment solve it?
- When is the app's disk enough?
- What about storing files in the database?
- How do you send the bot's attachments to object storage?
- Which option fits each scenario?
- How to do this on Square Cloud
- FAQs
A bot receives an image in a command, saves the link in the database and uses that link in an embed. It works for a few days. Then the embed shows up without the image and the link returns an error. Nothing changed in the code: the link expired.
This guide explains why that happens and compares the four ways to store a bot's images and files: re-uploading the attachment, the app's disk, the database and object storage. At the end there is a discord.js example that copies the attachment to an S3 bucket, plus a recommendation for each scenario.
Why does a Discord attachment link stop working?#
Every file sent to Discord, by people or by bots, lives on its CDN, and the official documentation states that these attachment links are signed and have an expiry time. An attachment link looks like this:
https://cdn.discordapp.com/attachments/<channel-id>/<attachment-id>/photo.png?ex=<hex>&is=<hex>&hm=<signature>ex is when the link expires and is is when it was issued, both as hex timestamps. hm is the signature, valid until the link expires.
Discord refreshes these links on its own in a few cases. Inside the app, anyone who opens the channel always sees a valid link. When your bot receives a message through the API (by fetching it with channel.messages.fetch, for example), its links are valid at that moment. And, according to the documentation, when you pass a CDN link into fields such as an embed image, you can send the link without the parameters, and Discord refreshes it when rendering. Avatars, emojis and the other CDN endpoints that aren't attachments are not signed and don't expire.
The practical result: saving an attachment link in your database is not saving the file. The refresh covers display inside Discord as long as the original attachment exists, but it doesn't let you download the file later, show it on a website or keep it if the message is deleted. Fetching the message again also depends on the bot still having access to the channel.
Which criteria matter?#
- How long the file has to exist. An image generated for a single reply doesn't need to be stored. A custom banner, a receipt or a ticket attachment needs to last for months.
- Who reads the file. Only Discord, or also a website, a web dashboard for the bot or another application.
- How many processes access it. A bot in a single process can use the local disk. A bot with sharding across several machines, or with a separate website, needs a place reachable over the network.
- Volume and size. A few images of a few KB fit anywhere. Thousands of multi-MB files change the math.
- Privacy. Files uploaded by users, such as documents and payment screenshots, shouldn't be open to anyone who has the link.
Does re-uploading the attachment solve it?#
For files the bot generates on the fly, such as a level card drawn with canvas, a chart or a report, the best option is often to store nothing: generate the file and send it as an attachment of the reply. The embed can point at that attachment with the attachment:// scheme:
import { AttachmentBuilder, EmbedBuilder } from "discord.js";
// buffer: a PNG generated by the bot (with @napi-rs/canvas, for example)
const file = new AttachmentBuilder(buffer, { name: "level.png" });
const embed = new EmbedBuilder()
.setTitle("Your level")
.setImage("attachment://level.png");
await interaction.reply({ embeds: [embed], files: [file] });There is no storage cost, and nothing expires on your side, because the file is recreated each time. The limits are Discord's: the API reference sets a maximum size per file, which goes up with the server's Boost tier, and the message request has its own cap. In embeds, the attachment:// scheme only accepts .jpg, .jpeg, .png, .webp and .gif.
Using a private channel as a file dump, re-uploading everything the bot needs to keep, is a different story. It works for a handful of files, but every read becomes an API call (subject to rate limits), the link still expires, anyone with permission can delete the message, and organizing or deleting files in bulk turns into manual work.
When is the app's disk enough?#
Saving the file to a folder on the server (./data/uploads) is the simplest path: no extra service, fast reads and no per-request cost. It suits a small bot running as one process with few files, and caches that can be rebuilt.
The limits show up as the project grows. On platforms with ephemeral disks, files vanish on the next deploy or restart, as explained in uploaded files that disappear after a deploy. A disk belongs to one machine: shards on different servers, or a website that needs to show the images, can't see the folder. And backups are up to you. The full comparison is in object storage or the app's disk.
What about storing files in the database?#
Databases accept binary data (BLOB in MySQL, bytea in PostgreSQL, GridFS in MongoDB), and for a few small files that works. But every image bloats the database, makes backups heavier and has no URL of its own: to show the image in an embed, the bot has to read the bytes and upload them again. The details are in images in the database or in object storage.
The database's real job is the metadata: the file's key in storage, who uploaded it, on which server, its size and its type. To choose the bot's database, see which database to use for your Discord bot.
How do you send the bot's attachments to object storage?#
Object storage keeps files by key, is reachable over the network from any process, grows without you resizing disks and gives each file a URL. For a bot, the flow is: receive the attachment, download it while the link is still valid, upload it to the bucket and save the key in the database.
The example creates a /store command that receives a file and copies it to any S3-compatible storage. Install the dependencies with npm install discord.js @aws-sdk/client-s3 @aws-sdk/s3-request-presigner, save it as bot.mjs and set the DISCORD_TOKEN, S3_ENDPOINT, S3_REGION, S3_BUCKET, S3_ACCESS_KEY and S3_SECRET_KEY environment variables:
import { GetObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { Client, Events, GatewayIntentBits, MessageFlags, SlashCommandBuilder } from "discord.js";
const s3 = new S3Client({
endpoint: process.env.S3_ENDPOINT, // omit it on AWS
region: process.env.S3_REGION ?? "us-east-1",
forcePathStyle: true,
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_KEY,
},
// Not every compatible service accepts the checksums the SDK sends by default
requestChecksumCalculation: "WHEN_REQUIRED",
responseChecksumValidation: "WHEN_REQUIRED",
});
const BUCKET = process.env.S3_BUCKET;
const MAX_BYTES = 8 * 1024 * 1024; // the largest file your bot agrees to store
const command = new SlashCommandBuilder()
.setName("store")
.setDescription("Stores a file in the bot's storage")
.addAttachmentOption((o) => o.setName("file").setDescription("The file").setRequired(true));
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, async (c) => {
await c.application.commands.set([command.toJSON()]); // global registration
console.log(`Logged in as ${c.user.tag}`);
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.commandName !== "store") return;
const attachment = interaction.options.getAttachment("file", true);
if (attachment.size > MAX_BYTES) {
await interaction.reply({ content: "File too large.", flags: MessageFlags.Ephemeral });
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
// Download now, while Discord's signed link is still valid
const response = await fetch(attachment.url);
if (!response.ok) throw new Error(`download failed: ${response.status}`);
const body = Buffer.from(await response.arrayBuffer());
const name = attachment.name.replace(/[^\w.-]/g, "_");
const key = `discord/${interaction.guildId ?? "dm"}/${interaction.user.id}/${attachment.id}-${name}`;
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: body,
ContentType: attachment.contentType ?? "application/octet-stream",
}),
);
// Save the key in your database; this link is temporary (1 hour)
const link = await getSignedUrl(s3, new GetObjectCommand({ Bucket: BUCKET, Key: key }), {
expiresIn: 3600,
});
await interaction.editReply(`Stored as \`${key}\`. Link valid for 1 hour: ${link}`);
} catch (error) {
console.error(error);
await interaction.editReply("Couldn't store the file.");
}
});
client.login(process.env.DISCORD_TOKEN);Three choices in the example matter. The bot downloads the attachment right away, while the signed link is valid, instead of saving the link. The key includes the server, the user and the attachment ID, which avoids collisions and makes it easy to delete everything from one server later. And the reply uses a one-hour presigned URL, because the bucket is private.
For images that appear in embeds for months, such as banners and welcome backgrounds, a presigned URL won't do, for the same reason as Discord's link: it expires. Put those files in a public bucket and use the permanent URL in setImage. Files uploaded by users, such as documents, stay in the private bucket. The difference is explained in public or private files.
Which option fits each scenario?#
| Scenario | Where to store |
|---|---|
| Image generated on the fly (level, leaderboard, chart) | Don't store it: generate it and send it as an attachment |
| Image configured per server (banner, welcome background) | Public object storage, key in the database |
| Files uploaded by users (tickets, receipts) | Private object storage, presigned URL when reading |
| Small bot, one process, few files | The app's disk, if it is persistent |
| Cache of images downloaded from external APIs | The app's disk, with periodic cleanup |
| Icons and thumbnails of a few KB | Database or object storage; object storage if the volume grows |
| Bot sharded across several machines or with its own website | Object storage |
When in doubt, use object storage for everything that has to survive and the database for the metadata.
How to do this on Square Cloud#
On Square Cloud, the bot and its files can live in the same account. Blob Storage comes with every plan, Hobby included, starting at R$12.49 per month, with a storage quota included (each plan's size is on the pricing page). It has an S3-compatible API, so the example above runs after changing only the variables: S3_ENDPOINT=https://s3-blob.squarecloud.app, S3_REGION=auto and the S3 keys you derive from an API key in the "S3 access" tab of the dashboard.
Buckets are fixed per account. Use S3_BUCKET=public for images that appear in embeds, served by a global edge CDN, and S3_BUCKET=private for user files, which open through a SigV4 presigned URL of up to 7 days, a temporary link of up to 24 hours or a share link of up to 30 days that can be revoked. There is no egress or ingress fee, and each file can be up to 10 GB.
The app's disk is also persistent across restarts and deploys: a new upload overwrites only the files in the ZIP, so a small cache stays in place. For anything that has to last and be read outside the bot, Blob is the place.
Blob Storage
S3-compatible object storage with no egress fees
FAQs
Do Discord image links expire?
Yes. Discord CDN attachment links are signed, with the ex, is and hm parameters, and have an expiry time. When the bot fetches the message again through the API, it gets a link that is valid at that moment.
Can I use a private Discord channel as my bot's storage?
It works for a handful of files, but it's fragile: the link expires, the message can be deleted, the bot can lose access to the channel and every read is an API call. For files you need to keep, use object storage.
What is the maximum file size a bot can upload to Discord?
It depends on the server: according to Discord's documentation, the limit applies to each file, has a default value and goes up with the server's Boost tier, and the whole message request has its own cap. In interactions, the attachment_size_limit field gives the limit for that context, in bytes.
Should I store my bot's images in the database?
Usually not. Files bloat the database, slow down backups and have no URL of their own. Store the file in object storage and keep the key and metadata, such as owner, server and size, in the database.
More in Storage
See all 24 articles- What is a presigned (signed) URL?A presigned URL is a temporary link to a private file that works without login or credentials. See how it works, its limits and when to use it.
- What is object storage?Object storage keeps files as objects with a key and metadata, accessed over an HTTP API. See how it works, what it is for and where its limits are.
- What does 'S3-compatible' storage mean?S3 is Amazon's object storage and its API became the industry standard. Learn what S3-compatible means, what differs between providers, and how to connect.
- Uploading large files: multipart and resumable uploadsMultipart upload splits a large file into parts that are sent in parallel and retried on their own. See the Python walkthrough, how to resume, and common mistakes.