【TypeScript】Get AWS S3 presigned URLs

AWS S3 presigned URLs allow access even for users without AWS credentials or permissions.

A presigned URL is a temporarily valid URL that is issued for a valid period of time.

目次

Retrieve files with AWS S3 presigned URLs.

The implementation is simple.

Set the Key in bucketParams to the name of the file in S3.
The signed URL is issued by passing it to GetObjectCommand to create an instance and setting it to the getSignedUrl function.

The argument of getSignedUrl takes expiresIn.
Here the number of seconds of the URL expiry time is set.

import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { Injectable } from '@nestjs/common';
import { createAwsCredentials } from '../config/aws/credentials';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class ImagesService {
  constructor(private prisma: PrismaService) {}

  async getImage(image_id: number): Promise<string> {
    const response = await this.prisma.ImagesModel.findUnique({
      where: { id: image_id },
    });

    if (!response) {
      return '';
    }

    const s3Client = new S3Client({
      region: <AWS_S3_REAGION>,
      credentials: createAwsCredentials(),
    });

    const bucketParams = {
      Bucket: <AWS_S3_BUCKET_NAME>,
      Key: response.image_name,
    };

    const command = new GetObjectCommand(bucketParams);
    return await getSignedUrl(s3Client, command, {
      expiresIn: 30,
    });
  }
}

AWS SDK Code Examples.

Related to createAwsCredentials.

Summary

It is important to read the documentation carefully for AWS relations.
Also, the infrastructure side is a more difficult image as it requires a lot of different knowledge.

よかったらシェアしてね!
目次