Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(nextjs): Fix server actions detection #3995

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/selfish-trainers-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clerk/nextjs": patch
---

Fix server actions detection
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please state what's the impact for the end user here?

4 changes: 4 additions & 0 deletions packages/nextjs/src/server/nextFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ type NextFetcher = Fetcher & {
* Full type can be found https://github.com/vercel/next.js/blob/6185444e0a944a82e7719ac37dad8becfed86acd/packages/next/src/client/components/static-generation-async-storage.external.ts#L4
*/
interface StaticGenerationAsyncStorage {
/**
* Available for >[email protected]
* A string with a suffix of `/page` or `/route` dictating usage from a page.tsx or a route.tsx file
*/
readonly pagePath?: string;
}

Expand Down
65 changes: 46 additions & 19 deletions packages/nextjs/src/server/protect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,38 +110,65 @@ export const createProtect = (opts: {
}) as AuthProtect;
};

/**
* Detects a request that will trigger a server action
* Can be used from the Edge Middleware and during rendering
*/
const isServerActionRequest = (req: Request) => {
return (
!!req.headers.get(nextConstants.Headers.NextUrl) &&
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Next-url as a header has been dropped from request to server actions since 14.1.0 way before 14.2.2 where our page detection started to fail.

(req.headers.get(constants.Headers.Accept)?.includes('text/x-component') ||
req.headers.get(constants.Headers.ContentType)?.includes('multipart/form-data') ||
Copy link
Member Author

@panteliselef panteliselef Aug 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking against multipart is not realistic. The following example will fire a request with Content-type text/plain;charset=UTF-8

'use client';

import { addItem2 } from '../actions';

export default function AddToCart() {
  return (
    <button
      type='button'
      onClick={() => {
        addItem2({ some: 'data' });
      }}
    >
      Click
    </button>
  );
}

!!req.headers.get(nextConstants.Headers.NextAction))
req.headers.get(constants.Headers.Accept)?.includes('text/x-component') &&
!!req.headers.get(nextConstants.Headers.NextAction)
);
};

/**
* Attempts to detect when a request results in a page being displayed
* *Attention*:
* When used within the Edge Middleware this utility will mistakenly detect a Route Handler as a Page
Comment on lines +126 to +127
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this problematic for our middleware in any scenarios you can think of?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@panteliselef related to Bryce's question above, what does this comment mean for the middleware's auth() helper?

*/
const isPageRequest = (req: Request): boolean => {
return (
req.headers.get(constants.Headers.SecFetchDest) === 'document' ||
req.headers.get(constants.Headers.SecFetchDest) === 'iframe' ||
req.headers.get(constants.Headers.Accept)?.includes('text/html') ||
isAppRouterInternalNavigation(req) ||
isPagesRouterInternalNavigation(req)
(req.headers.get(constants.Headers.SecFetchDest) === 'document' ||
req.headers.get(constants.Headers.SecFetchDest) === 'iframe' ||
req.headers.get(constants.Headers.Accept)?.includes('text/html') ||
isAppRouterInternalNavigation(req) ||
isPagesRouterInternalNavigation(req)) &&
!isServerActionRequest(req) &&
!isAppRouteRoute(getPagePathAvailable())
);
};

const isAppRouterInternalNavigation = (req: Request) =>
(!!req.headers.get(nextConstants.Headers.NextUrl) && !isServerActionRequest(req)) || isPagePathAvailable();
// Since [email protected] the `next-url` header is being stripped before it can reach the rendering server, and it is only available when executed inside the Next.js Edge Middleware
(!!req.headers.get(nextConstants.Headers.NextUrl) || isAppPageRoute(getPagePathAvailable())) &&
!isServerActionRequest(req);

/**
* Detects usage inside a page.tsx file in App Router
* Found in the Next.js repo
* https://github.com/vercel/next.js/blob/0ac10d79720cc950df96bd9d4958c9be0c075b6f/packages/next/src/lib/is-app-page-route.ts
*/
export function isAppPageRoute(route: string): boolean {
return route.endsWith('/page');
}

const isPagePathAvailable = () => {
/**
* Detects usage inside a route.tsx file in App Router
* Found in the Next.js repo
* github.com/vercel/next.js/blob/0ac10d79720cc950df96bd9d4958c9be0c075b6f/packages/next/src/lib/is-app-route-route.ts
* In case we want to handle router handlers and server actions differently in the future
*/
export function isAppRouteRoute(route: string): boolean {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, I think they are called "route handlers": https://nextjs.org/docs/app/building-your-application/routing/route-handlers

Suggested change
export function isAppRouteRoute(route: string): boolean {
export function isAppRouteHandler(route: string): boolean {

return route.endsWith('/route');
}

/**
* Returns a string that can either end with `/page` or `/route` indicating that the code run in the context of a page or a route handler.
* These values are only available during rendering (RSC, Route Handlers, Server Actions), and will not be populated when executed inside the Next.js Edge Middleware
*/
const getPagePathAvailable = () => {
const __fetch = globalThis.fetch;
return Boolean(isNextFetcher(__fetch) ? __fetch.__nextGetStaticStore().getStore()?.pagePath : false);
return isNextFetcher(__fetch) ? __fetch.__nextGetStaticStore().getStore()?.pagePath || '' : '';
};

const isPagesRouterInternalNavigation = (req: Request) => !!req.headers.get(nextConstants.Headers.NextjsData);

// /**
// * In case we want to handle router handlers and server actions differently in the future
// */
// const isApiRouteRequest = (req: Request) => {
// return !isPageRequest(req) && !isServerActionRequest(req);
// };
Loading