Next.js Discord

Discord Forum

How can I run code during build?

Unanswered
Large oak-apple gall posted this in #help-forum
Open in Discord
Large oak-apple gallOP
I have a function that checks that the environment variables required by my app are correctly defined.

Currently that function runs inside a middleware which fails without giving any meaningful information unless you check the server logs.

I would like to call that function during the build instead, so that the build fails if the function finds missing env variables.

What would be the best way to accomplish this?

13 Replies

Large oak-apple gallOP
thanks!
Large oak-apple gallOP
hmm, the only issue is that my env validation code is in TypeScript
not sure I can import from next.config.js…?
you have to use js and for typing, // @ts-check with jsdoc i guess
or you can also use a typescript file and run it before next build
Large oak-apple gallOP
how would I do that?
@Large oak-apple gall how would I do that?
use something like ts-node then
- "build": "next build",
+ "build": "ts-node utils/check-env.ts && next build"
Large oak-apple gallOP
oh interesting, I'll look into it
so I assume there's no other built-in "post-build" hook in Next?
that would run in the same environment as the rest of your Next code
no there isn't anything like that