When it comes to serving authenticated images within your NestJS application, a useful approach is to leverage Signed URLs with Minio. These Signed URLs grant temporary access to resources without requiring an Authorization header, making them ideal for situations where you need to serve images in <img> tags.
// Setting up an Image controller to handle signed URLs
@Controller('images')
export class ImageController {
constructor(private imageService: ImageService) {}
@Get(':filename')
@UseGuards(AuthGuard()) // Route protection with authentication
async getImage(@Param('filename') filename: string, @Req() req: Request) {
try {
const signedUrl = await this.imageService.generateSignedUrl(filename, req.user);
return { signedUrl };
} catch (error) {
// Error handling
}
}
}
// Service responsible for generating signed URLs for images
@Injectable()
export class ImageService {
constructor(private minioClient: MinioClient) {}
async generateSignedUrl(filename: string, user: any): Promise<string> {
// Logic for creating a signed URL for the image based on the filename and user
// Utilize the Minio SDK to generate the signed URL
// Example:
// const signedUrl = await this.minioClient.presignedGetObject('bucketName', filename);
return signedUrl;
}
}
Example of implementation:
<img src="signedUrlFromBackend" alt="Image" />