sst / open-next

Open source Next.js serverless adapter
https://open-next.js.org
MIT License
3.7k stars 111 forks source link

Middleware ignored when deploying to prod #376

Closed EAlf91 closed 4 months ago

EAlf91 commented 4 months ago

I've been struggling with this for a while now

I use latest nextjs 14 using the app router and put my middleware.ts into the root of my project as the documentation suggests.

When running npm run dev locally everything works fine and the middleware triggers.

But when running a deployment and I hit the cloudfront routes I just get routed through. No middleware is being triggered.

This is a serious issue as it makes secured routes public available.

This is my middleware setup:


/**
 * BIG WARNING
 * THIS IS NOT WORKING IN PROD middleware seems to be ignored
 */
'use client'
import { fetchAuthSession } from 'aws-amplify/auth/server';
import { NextRequest, NextResponse } from 'next/server';
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';
import { LINKS } from '@/utils/links/links';

export async function middleware(request: NextRequest) {
  const response = NextResponse.next();
  const authenticated = await runWithAmplifyServerContext({
    nextServerContext: { request, response },
    operation: async (contextSpec) => {
      try {
        const session = await fetchAuthSession(contextSpec);
        return session.tokens !== undefined;
      } catch (error) {
        console.log(error);
        return false;
      }
    },
  });

  if (authenticated) {
    return response;
  }

  return NextResponse.redirect(new URL(LINKS.ROOT_AUTH_LOGIN, request.url));
}

export const config = {
  matcher: [
    '/api/login/'
  ]
};
conico974 commented 4 months ago

Are you running on windows? Open-next don't work well there, you need to use WSL

EAlf91 commented 4 months ago

@conico974 Thanks! Just deployed on wsl and it worked. Would have never guessed that this was the problem. You saved me tons of time. 👍 I'll close the issue