Reputation: 1889
I have a Next.js API route which needs to access a local file, but __dirname is not defined when I use it within an API route.
Is it possible to get the current directory from within a Next route?
Upvotes: 4
Views: 5120
Reputation: 422
In order to access the root directory, or any directory for that matter, you can used next.config.js
to set a webpack alias. Example:
// Inside next.config.js
module.exports = {
webpack: (config) => {
config.resolve.alias = {
...config.resolve.alias,
'~': __dirname,
};
}
Now ~
, when used to path to resources, will resolve to the value of __dirname
.
Alternatively you could use next.js's client env if you're on next.js 8+. Example:
// inside next.config.js
module.exports = {
env: {
ROOT: __dirname,
}
}
Now using process.env.ROOT
gives you access to __dirname
.
Upvotes: 2