Repository: auth0/nextjs-auth0
Pull request #1263 (2023-06-23 12:50:20)

Fix for setting custom cookies in `withMiddlewareAuthRequired`
### 📋 Changes

Similar fix to https://github.com/auth0/nextjs-auth0/pull/1236 for merging any cookies set in custom middleware with the session cookie.

### 📎 References

Fixes https://github.com/auth0/nextjs-auth0/issues/1253



Patch:
diff --git a/src/helpers/with-middleware-auth-required.ts b/src/helpers/with-middleware-auth-required.ts
index 80034ef6..a65a6c57 100644
--- a/src/helpers/with-middleware-auth-required.ts
+++ b/src/helpers/with-middleware-auth-required.ts
@@ -1,5 +1,6 @@
 import { NextMiddleware, NextRequest, NextResponse } from 'next/server';
 import { SessionCache } from '../session';
+import { splitCookiesString } from '../utils/middleware-cookies';
 
 /**
  * Protect your pages with Next.js Middleware. For example:
@@ -77,10 +78,11 @@ export default function withMiddlewareAuthRequiredFactory(
 
       if (res) {
         const headers = new Headers(res.headers);
-        const cookies = headers.get('set-cookie')?.split(', ') || [];
-        const authCookies = authRes.headers.get('set-cookie')?.split(', ') || [];
-        if (cookies.length || authCookies.length) {
-          headers.set('set-cookie', [...authCookies, ...cookies].join(', '));
+        const authCookies = splitCookiesString(authRes.headers.get('set-cookie')!);
+        if (authCookies.length) {
+          for (const cookie of authCookies) {
+            headers.append('set-cookie', cookie);
+          }
         }
         return NextResponse.next({ ...res, status: res.status, headers });
       } else {
diff --git a/src/utils/middleware-cookies.ts b/src/utils/middleware-cookies.ts
index fbe23533..5390f587 100644
--- a/src/utils/middleware-cookies.ts
+++ b/src/utils/middleware-cookies.ts
@@ -33,7 +33,7 @@ export default class MiddlewareCookies extends Cookies {
  * Handle cookies with commas, eg `foo=; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
  * @source https://github.com/vercel/edge-runtime/blob/90160abc42e6139c41494c5d2e98f09e9a5fa514/packages/cookies/src/response-cookies.ts#L128
  */
-function splitCookiesString(cookiesString: string) {
+export function splitCookiesString(cookiesString: string) {
   if (!cookiesString) return [];
   const cookiesStrings = [];
   let pos = 0;


Test patch:
diff --git a/tests/helpers/with-middleware-auth-required.test.ts b/tests/helpers/with-middleware-auth-required.test.ts
index b5bf9e1e..a799697a 100644
--- a/tests/helpers/with-middleware-auth-required.test.ts
+++ b/tests/helpers/with-middleware-auth-required.test.ts
@@ -183,7 +183,16 @@ describe('with-middleware-auth-required', () => {
     };
     const res = await setup({ user: { name: 'dave' }, middleware });
     expect(res.status).toEqual(200);
-    expect(res.headers.get('set-cookie')).toMatch(/^appSession=.+, foo=bar;/);
+    expect(res.headers.get('set-cookie')).toMatch(/appSession=/);
+    expect(res.headers.get('set-cookie')).toMatch(/foo=bar;/);
+  });
+
+  test('should set status from custom middleware', async () => {
+    const middleware = () => {
+      return new NextResponse(null, { status: 400 });
+    };
+    const res = await setup({ user: { name: 'dave' }, middleware });
+    expect(res.status).toEqual(400);
   });
 
   test('should set just a custom cookie when session is not rolling', async () => {