Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use import to read a JSON file in a Next.js 13 API?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
  ...
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading