Alexiuscrow
Alexiuscrow

Reputation: 785

How to get the directory path in a Next.js project deployed to Vercel?

In my Next.js project, I am using Fluent (https://projectfluent.org) for internationalization. Fluent uses .ftl files for locales.

My project's abstract structure:

my-app/
├─ src/
│  ├─ app/
│  ├─ locales/
│  │  ├─ uk.ftl
│  │  ├─ fr.ftl
│  ├─ file.ts

How can I get the path to the locales directory, from the server-side file.ts file?

It's important to note that the project is deployed on the Vercel platform.
I tried to use process.cwd() + '/src/locales', and got the error [Error]: ENOENT: no such file or directory, scandir '/var/task/src/locales'. — It didn't work for me..

Please don't suggest placing the locales inside the public dir.

Upvotes: 0

Views: 1491

Answers (2)

Yasas Maddumage
Yasas Maddumage

Reputation: 1

I'm not sure if this will be helpful, but I encountered a similar issue with my Express.js project. The project worked perfectly locally, but when I deployed it to Vercel, I faced errors because Vercel adds the '/var/task/' prefix to every relative path.

I modified the code by adding const path = require('path');, which is a built-in Node.js module that provides utilities for working with file and directory paths. I then updated the relative paths accordingly. For instance, I changed const collegeData = require("./modules/collegeData"); to const collegeData = require(path.join(__dirname, "modules", "collegeData"));. This method ensures that the paths are constructed correctly regardless of the environment. I also updated './data/students.json' to path.resolve(__dirname, '../data/courses.json');.

Can you implement something similar?

Upvotes: 0

Alexiuscrow
Alexiuscrow

Reputation: 785

As it turned out, the localization files (and as a result the locales dir) were missed due to the tracing step and the @vercel/nft package.

Solved the issue with:

import path from 'path';

const dirPath = path.join(process.cwd(), '/src/locales')

Also, the output parameter in next.config.js will be useful to see which files are included in the build. More info: https://nextjs.org/docs/app/api-reference/next-config-js/output.

Hope someone finds this useful and saves time.

Upvotes: 0

Related Questions