In this post, I practice to create API in Next.js and AWS S3.
I add GET function in route.ts which made last time.
export const GET = async () => {
return NextResponse.json({ message: 'Hello World!'}, { status: 200 });
}
I want to get the test state when I click the button. For eventHandle, create handler function:
const testGetHandler = async () => {
const response = await fetch('/api', {
method: 'GET',
})
if (response.status === 200) {
const result = await response.json();
setGetTestState(result.message);
}
}
Add button and p tag for presenting result.
<button onClick={testGetHandler} className="bg-gray-300 px-6 py-4 text-gray-900">Test Get button</button>
<p className="text-9xl">{getTestState}</p>
Cool. :D
I'm going to change the operation of GET function from simly delivering a test state to retrieving an image that I uploaded to my S3 bucket.
Updated GET function:
export const GET = async (req: NextRequest) => {
const { searchParams } = new URL(req.url);
const key = searchParams.get("key");
if (!key) {
return NextResponse.json({ error: "Missing 'key' parameter" }, { status: 400 });
}
const fileParams = {
Bucket: Bucket,
Key: key,
}
const s3Response = await s3.send(new GetObjectCommand(fileParams));
const stream = s3Response.Body as ReadableStream;
const headers = new Headers();
headers.set("Content-Type", s3Response.ContentType || "application/octet-stream");
return new Response(stream, { headers });
};
Handler function:
const getImageHandler = async () => {
const response = await fetch(`/api?key=Screenshot 2025-02-22 at 1.31.05 PM.png`);
if (response.ok) {
const blob = await response.blob();
const url = URL.createObjectURL(blob);
setImageSrc(url);
}
}
I directly put the name of image into api key parameter.
:D
Finally I'm going to add DELETE api.
export const DELETE = async (req: NextRequest) => {
const { searchParams } = new URL(req.url);
const key = searchParams.get("key");
if (!key) {
return NextResponse.json({ error: "Missing 'key' parameter" }, { status: 400 });
}
const fileParams = {
Bucket: Bucket,
Key: key,
}
await s3.send(new DeleteObjectCommand(fileParams))
return NextResponse.json({ status: 200 });
}
Handler function:
const deleteHandler = async () => {
const result = await fetch('/api?key=Screenshot 2025-02-22 at 1.31.05 PM.png', {
method: 'DELETE',
}).then((res) => res.json());
if (result.status === 200) {
alert('Successfully deleted the image');
}
}
1: click the delete image button.
2: check that the file has been removed from S3 storage.
All functions are working successfull!
'공부 > 코딩' 카테고리의 다른 글
와플 스튜디오 루키 과정 복습하기 6 - YAML과 Github Actions (0) | 2025.02.28 |
---|---|
와플 스튜디오 루키 과정 복습하기 5 - Distribution with AWS EC2 (No Versel) (0) | 2025.02.25 |
와플 스튜디오 루키 과정 복습하기 - 3: AWS S3, image upload (0) | 2025.02.22 |
와플 스튜디오 루키 과정 복습하기 - 2: fetch 와 supabase 기본 세팅 (0) | 2025.02.20 |
와플 스튜디오 루키 과정 복습하기 - 1: 개발환경 세팅 (Next.js, Bun) (0) | 2025.02.19 |