Problem:
I’m working with Next.js 13 and utilizing the App Router feature. Currently, I have an API route that reads a file from a resources folder, specifically a language folder. Here’s the structure of my API:
// app/api/file/[lang]/write/route.ts
import { APIResponseType } from '@/models/api/response';
import { NextRequest, NextResponse } from 'next/server';
type Params = {
params: {
lang: string;
};
};
export async function GET(req: NextRequest, { params: { lang } }: Params) {
const data = await import(`../../../../../languages/${lang}.json`);
return NextResponse.json<APIResponseType>({
message: 'Get language successfully',
data: data
});
}
I’ve tested this API, and it’s working as expected.
However, I’m curious if there’s a more efficient or recommended approach for reading files from the Next.js resources directory. Any insights or alternative methods would be greatly appreciated.
Solution:
You can use resolve function in path
module like this.
import path from 'path';
export async function GET(req: NextRequest, { params: { lang } }: Params) {
const languageFilePath = path.resolve('resources', 'languages', `${lang}.json`);
const data = await import(languageFilePath);
...
}