#Read config file with node fs in next.js middleware

8 messages · Page 1 of 1 (latest)

trim musk
#

I have a challenge with reading a config file and using that file in next.js middleware, but middleware is using edge runtime only and therefore node fs can't be used.
However, the project will be deployed and handled by the company's infrastructure and therefore I'm pretty sure the middleware is running with nodejs runtime(?)
What I'm trying to accomplish is something like this (example with very simplified pseudo code below) and wonder if someone have any idea how to make a workaround to make this work? Or have solved something similar in another way?

  // config.ts
   import {readFileSync, watchFile} from 'node:fs';
   import {parse as parseYAML} from 'yaml';

   const getConfig = () => {
     let config = {};
     const configYAML = parseYAML(readFileSync(file, 'utf8'));
     
     watchFile(file, {interval: 5007}, () => {
         // return updated config data
         return;
     });

    return configYAML;
   };
   
   export default getConfig;
// middleware.ts
import getConfig from './config';

const middleware = async (request: NextRequest) => {
   try {
      const config = getConfig();
      // use config
   } 
   catch (error) {
      // throw error
   }
};

export default middleware;
light robin
#

I'm having the same problem!

#

Were you ever able to find a solution?

light robin
#

I ended up just injecting via an environment variable from next.config.js

plush quest
mossy urchinBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer
light robin
#

It's strange that there isn't a way to have the Middleware run on server

#

I'm running it on my own infrastructure