I am trying to deploy my Next JS 14 app to AWS with OpenNext. Here are the OpenNext docs regarding Next JS middlware, but unfortunately the documentation is not very thorough:
OpenNext previously was not a great option for deploying Next JS 14 sites (according to my understanding) because they did not treat middleware real great. From what I have found, they just packaged middleware up with any other server side code and cached it (I think in cloudfront). This would create problems, because it meant that middleware would get cached and stop running - a major problem if middleware is handling any authentication / authorization and protected routes (which are primary candidate usages for middleware).
However, with the semi-recent release of OpenNext v.3, they created a way to create external middleware, meaning that middleware can be separated from the rest of the server side code so that it runs prior to each request.
This is an option, but must be configured in the open-next.config.ts file:
const config = {
default: {},
middleware: {
external: true,
}
}
export default config;
Upon deploying, I am running into a problem. OpenNext is attempting to put the middleware function on Lambda@edge, and Lambda@edge does not support environment variables (as far as I can tell). This seems like yet another major shortcoming of the OpenNext deployment process - for example, since one primary usage of middleware is authentication, I need to make an api call in my middleware to my authentication route, meaning I have an environment variable.
So my question is, what do I do? I need the environment variable in my middleware, but this is preventing OpenNext from deploying the middleware to Lambda@edge. Is there some way to configure an environment variables store on Lambda@edge functions? Or maybe some way to tell OpenNext to deploy middleware to a normal Lambda function, as opposed to a Lambda@edge function? But also, if that is possible, will removing the middleware from Lambda@edge cause problems with any client component that are hosted in cloudfront?
I now this explanation may sound a bit tedious, but I am not an AWS expert and haven't deployed to this before (I have always used vercel prior to now), so any tips or explanations to help me understand this better sure would be appreciated.