I need to compute and cache new data at build time that is required by both the frontend and backend API routes. Is there any way to read the static properties generated at build time by API routes? The API routes are publicly accessible, so I can't just pass the data from the frontend.
CodePudding user response:
All build artifacts are saved in .next
folder, that's outside application source, therefore your code won't be able to access it.
If data you're getting in getStaticProps
is time consuming to compute, I'd save it in some cache
and then read from this cache in your API routes.
UPDATE: I lied, I played around and it's actually possible to access cached page data, but there are some caveats.
Build artifacts for given page are saved in .next/server/pages/
. Exported static props are stored in a JSON file, that matches page path. E.g. static props for /contact
live in .next/server/pages/contact.json
.
Those files are deleted when you do yarn build
, therefore you can't simply import them with
import data from '../../.next/server/pages/contact.json'
in your code, as that will break the build because of your attempt to import nonexistent file.
What you could do, is loading this file this way:
const cacheDirectory = path.join(process.cwd(), '.next/server/pages/');
const fileContents = await fs.readFile(cacheDirectory '/contact.json', 'utf8');
This will build just fine and work when you do yarn start
. But... it won't work when you do yarn dev
, because this command clears the build folder. To work around that, you could check for NODE_ENV
value and run this logic in production
mode only and use some mock data in this scenario.