I am using NextJS to manage a small storefront and admin panel. The current flow is: Any images added by the admin are saved to a folder with the item’s name, and after getting an OK response from ImageKit, I save item data in MongoDB (name, price, description, URLs to the images in ImageKit, etc.).
Saving images using the NextJS SDK works fine, but the problem I have is deleting folders (either by an admin’s action or as a safety measure caused by a failed MongoDB insertion). I cannot find any information on how to do this with the NextJS SDK, or if it is even possible, but trying to do it with the API is not working.
Also, the documentation is a little confusing since the example for Javascript’s fetch is completely different to the practical example, which seems to use a Node SDK. I tried following the request example rather than the Node example since I don’t know if having both the NextJS and the Node SDKs installed would conflict with each other.
This is the code I currently have in my app’s API endpoint
app/api/store/items/images/route.ts:
/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextRequest, NextResponse } from "next/server";
export async function DELETE(req: NextRequest) {
// TODO: Auth check!
// Encoding key to base64
const privateKey = process.env.IMAGEKIT_PRIVATE_KEY;
if (!privateKey) {
console.error('No ImageKit Private Key provided');
return NextResponse.error();
}
// Adding a colon at the end of my private key as
// instructed by the documentation
const keyBuffer = Buffer.from(`${privateKey}:`, 'utf-8');
const encodedKey = keyBuffer.toString("base64");
// Getting the folderPath from the body of the request to
// my API's endpoint, to pass it along to IK's API
const body = await req.json();
// Checking everything's correct up to this point
console.log('Folder to delete:', body.folderPath);
console.log('Private Key: ', privateKey);
// Calling ImageKit's API
try {
const response = await fetch(`https://api.imagekit.io/v1${body.folderPath}`,
{
method: 'DELETE',
headers: {
Accept: 'application/json',
Authorization: `Basic ${encodedKey}`
}
body: JSON.stringify({
folderPath: body.folderPath
})
});
const data = await response.json();
console.log('Path deleted succesfully.', data);
return NextResponse.json(data);
}
catch(error: any) {
console.error('Error deleting ImageKit folder', error.message);
return NextResponse.error();
}
}
This returns the following error:
{
"error": "Invalid CSRF Token"
}