-
Notifications
You must be signed in to change notification settings - Fork 27.1k
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Next.js API routes (and pages) should support reading files #8251
Comments
Just wanted to second that, trying to implement file uploading using API routes. I can get the file to upload but then need to be able to access it again to upload it to S3 bucket. |
I second this! Also, being able to read directories is very important for my company's usage as we keep our data like team members and blog posts in a content directory so we're looking for a way to require all files in the directory. |
The above PR will fix this! ☝️ 🙏 |
How about |
Hey @marlonmarcello, this is going to be possible. Stay tuned 😊 |
It's this already solved? |
Not yet, you can subscribe for #8334 |
@huv1k Many thanks! |
Is there a way to help this move forward more quickly? |
Worth noting: if you're using TypeScript, you can already import a JSON file as a module directly (make sure import myJson from '../../../some/path/my.json'; The shape of the JSON object is also automatically used as its type, so autocomplete is really nice. |
Workaround I'm using: # next.config.js
module.exports = {
serverRuntimeConfig: {
PROJECT_ROOT: __dirname
}
} and in the location you need the path import fs from 'fs'
import path from 'path'
import getConfig from 'next/config'
const { serverRuntimeConfig } = getConfig()
fs.readFile(path.join(serverRuntimeConfig.PROJECT_ROOT, './path/to/file.json')) I know this doesn't solve the need to reference files with paths relative to the current file, but this solves my very related use case (reading image files from a |
Saw in the PR this has changed a bit - any update on what the current plans are (or aren't)? Sounds like there are some strategies you don't want pursued, mind listing them + why so contributors can give this a shot? |
@ijjk Hope there will be some good documentation on how to use this properly too 👍 |
@ijjk that’s great news! I have a couple possibly stupid questions, but it’d be great if you could clarify them for everyone 🙂
cd /path/to/project
cd node_modules/.bin
./next
## Is process.cwd() in Next.js pages and API routes
## /path/to/project
## or
## /path/to/project/node_modules/.bin
## ? |
for me it worked |
@kachkaev this is specific to reading files inside server-side methods like API routes or The |
In case could be useful for someone to try, for me worked a combination of some comments, after lots of deploys. // next.config.js
module.exports = {
target: 'serverless',
experimental: { nftTracing: true },
} The folder with files called by the function inside resolve('./public/my-folder/my-file.txt') |
After some tries, this works for me on Accessing // next.config.js
module.exports = {
experimental: { outputFileTracing: true }
} // vercel.json
{
"functions": {
"pages/api/contact.js": {
"includeFiles": "email/template.mjml"
}
}
} // pages/api/contact.js
const { join, resolve } = require("path");
const { readFileSync } = require("fs");
export default async (req, res) => {
const templateDirectory = resolve(process.cwd(), "email");
const emailTemplate = readFileSync(join(templateDirectory, "template.mjml"), "utf8");
// ...
}; |
Hello @tvavrys , I tried this approach. It works when I use
I did change the base path to this:
so server to serverless (otherwise it doesn't work on and the
Would you have any idea what could be breaking it? Thanks. |
@ijjk I'm using something similar in our project right now: During build time, we receive data from a CMS which we write in a JSON file to be read during build and run time. The directory structure is ./json/<locale_for_website>/<actual_JSON_file> (so located in root of project). Everything seems to work during build and runtime both locally and deployed, except for revalidation: For some reason, process.cwd() returns a different value when revalidation of a ISR page is happening. During revalidation when a new file needs to be generated, we first use Do you have a good suggestion for this use case? Many thanks! |
So, the question is, how to access current directory of a page ? |
That's a different issue, and really, the directory does not exist as the JS. Ode gets bundled into one file. |
Hi, I have the same error, with I created a basic repo to reproduce the error: https://github.com/richard87/test-grpc |
I'm on Next.js 12 and I previously used @tvavrys's suggestion but this seems to be broken now. I have a serverless function that reads script files relative to the project's root and runs them when invoked from a Next.js page via http calls. It seems that exporting a unstable_includeFiles config prop for the serverless api file works:
and then a path to the file is simply
🤷 works but seems to be a temporary hack ? |
It works with // next.config.js
module.exports = {
outputFileTracing: true
} But, it doesn't work when file is "README.md", it's really weird. @ijjk Code as below: // vercel.json
{
"functions": {
"pages/api/contact.js": {
"includeFiles": "extensions/**/README.md"
}
}
} // pages/api/contact.js
import type { NextApiRequest, NextApiResponse } from "next";
import { resolve, join } from "path";
import { readFileSync } from "fs";
type Data = {
content: string;
};
type Error = {
error: string;
};
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data | Error>
) {
if (req.method === "GET") {
const { slugs } = req.query;
const slug = typeof slugs === "string" ? slugs : slugs[0];
const templateDirectory = resolve(process.cwd(), "extensions");
const emailTemplate = readFileSync(
join(templateDirectory, slug, "README.md"),
"utf8"
);
return res.status(200).json({
content: emailTemplate,
});
} else {
return res.status(404).json({
error: "Not Support Method",
});
}
}
|
@curly210102 |
@ijjk Oh sorry, the code snippet pasted in the above with a accidental omission, please take the repo as the prevailing. To illustrate the specific behavior of "README.md", I added "index.md" demo as a comparison. And remove the
|
Is there a solution for this? We need to be able to read some template files as well in an endpoint under @curly210102 did you find anything that could resolve the issue in your example? |
I have a slightly different permutation of the same problem. I reproduced it here: https://github.com/mtimofiiv/vercel-fonts-demo And it's deployed here: https://vercel-fonts-demo.vercel.app Readme file in the repo has all the things I tried – but basically I followed a bunch of different instructions from this thread plus also this one: |
When the
For (1), this may be due to relocation of the files in the process of deployment from development locations to operations locations. For (2), this can be due to pilot error (of course) or to incomplete Next.js configuration. When I encountered this issue, I was trying to read from the file system a GraphQL schema file. Those files are lightly-stylized blends of JSON and Javascript/Typescript - but they use a My local development build and run was fine but the Apparently, the See https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions Here’s the crucial sample advice:
Also be advised that when we modify the set of file extensions to be considered, we have to restate the default extensions - or else the files which were deployed will then get excluded - leaving a broken mess. (now to test this in my repo. If this is all true, I can remove some workaround stuff that might have worked but seems to have broken Dynamic Routing.) Update: this may help some people - but it isn't the right change for me. If I add Update: I gave up on attempting to get Next.js and Vercel to be able to deploy the non-code file to the pages/api area and to run the server less functions with This was an educational diversion into the details of Next.js and Vercel but isn't the major goal of what I am prototyping. I'll monitor for updates to this issue and refactor the bandaid area later. |
So I have had this same issue and I recently realised that I can just use Webpack Copy Plugin to enforce copying the required files to the bundle (within the However, on deployment to Vercel, it is not adding/hosting those files when I check the |
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
Feature request
Is your feature request related to a problem? Please describe.
It's currently not possible to read files from API routes or pages.
Describe the solution you'd like
I want to be able to call
fs.readFile
with a__dirname
path and have it "just work".This should work in Development and Production mode.
Describe alternatives you've considered
This may need to integrate with
@zeit/webpack-asset-relocator-loader
in some capacity. This plugin handles these types of requires.However, it's not a necessity. I'd be OK with something that only works with
__dirname
and__filename
(no relative or cwd-based paths).Additional context
Example:
The text was updated successfully, but these errors were encountered: