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

App router: Allow types for page params/searchParams for pages wrapped by withPageAuthRequired #1764

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
31 changes: 19 additions & 12 deletions src/helpers/with-page-auth-required.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type PageRoute<P, Q extends ParsedUrlQuery = ParsedUrlQuery> = (
) => Promise<GetServerSidePropsResultWithSession<P>>;

/**
* Objects containing the route parameters and search parameters of th page.
* Objects containing the route parameters and search parameters of the page.
*
* @category Server
*/
Expand All @@ -50,7 +50,7 @@ export type AppRouterPageRouteOpts = {
*
* @category Server
*/
export type AppRouterPageRoute = (obj: AppRouterPageRouteOpts) => Promise<React.JSX.Element>;
export type AppRouterPageRoute<PageProps> = (obj: PageProps) => Promise<React.JSX.Element>;

/**
* If you have a custom returnTo url you should specify it in `returnTo`.
Expand Down Expand Up @@ -124,8 +124,8 @@ export type WithPageAuthRequiredPageRouter = <
*
* @category Server
*/
export type WithPageAuthRequiredAppRouterOptions = {
returnTo?: string | ((obj: AppRouterPageRouteOpts) => Promise<string> | string);
export type WithPageAuthRequiredAppRouterOptions<PageProps> = {
returnTo?: string | ((obj: PageProps) => Promise<string> | string);
};

/**
Expand All @@ -136,7 +136,7 @@ export type WithPageAuthRequiredAppRouterOptions = {
* // app/protected-page/page.js
* import { withPageAuthRequired } from '@auth0/nextjs-auth0';
*
* export default function withPageAuthRequired(ProtectedPage() {
* export default withPageAuthRequired(function ProtectedPage() {
* return <div>Protected content</div>;
* }, { returnTo: '/protected-page' });
* ```
Expand All @@ -155,7 +155,7 @@ export type WithPageAuthRequiredAppRouterOptions = {
* // app/protected-page/[slug]/page.js
* import { withPageAuthRequired } from '@auth0/nextjs-auth0';
*
* export default function withPageAuthRequired(ProtectedPage() {
* export default withPageAuthRequired(function ProtectedPage({ params }: { params: { slug: string } ) {
* return <div>Protected content</div>;
* }, {
* returnTo({ params }) {
Expand All @@ -166,10 +166,17 @@ export type WithPageAuthRequiredAppRouterOptions = {
*
* @category Server
*/
export type WithPageAuthRequiredAppRouter = (
fn: AppRouterPageRoute,
opts?: WithPageAuthRequiredAppRouterOptions
) => AppRouterPageRoute;
export type WithPageAuthRequiredAppRouter = <
T extends {
params: T['params'] extends undefined ? undefined : { [K in keyof T['params']]: string };
searchParams: T['searchParams'] extends undefined
? undefined
: { [K in keyof T['searchParams']]: string | undefined };
}
>(
fn: (obj: T) => Promise<React.JSX.Element>,
opts?: WithPageAuthRequiredAppRouterOptions<T>
) => AppRouterPageRoute<T>;

/**
* Protects Page router pages {@link WithPageAuthRequiredPageRouter} or
Expand All @@ -190,8 +197,8 @@ export default function withPageAuthRequiredFactory(
const pageRouteHandler = pageRouteHandlerFactory(getConfig, sessionCache);

return ((
fnOrOpts?: WithPageAuthRequiredPageRouterOptions | AppRouterPageRoute,
opts?: WithPageAuthRequiredAppRouterOptions
fnOrOpts?: WithPageAuthRequiredPageRouterOptions | AppRouterPageRoute<unknown>,
opts?: WithPageAuthRequiredAppRouterOptions<unknown>
) => {
if (typeof fnOrOpts === 'function') {
return appRouteHandler(fnOrOpts, opts);
Expand Down
62 changes: 58 additions & 4 deletions tests/helpers/with-page-auth-required.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,68 @@
import { expectTypeOf } from 'expect-type';
import { NextResponse } from 'next/server';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { NextResponse } from 'next/server';
import { URL } from 'url';
import { login, setup, teardown } from '../fixtures/setup';
import { initAuth0 } from '../../src';
import { get } from '../auth0-session/fixtures/helpers';
import { login as appRouterLogin } from '../fixtures/app-router-helpers';
import { withApi, withoutApi } from '../fixtures/default-settings';
import { get } from '../auth0-session/fixtures/helpers';
import { initAuth0 } from '../../src';
import { login, setup, teardown } from '../fixtures/setup';

describe('with-page-auth-required ssr', () => {
describe('typed app route', () => {
let redirect: jest.Mock;

beforeEach(() => {
jest.doMock('next/headers', () => ({ cookies: () => new NextResponse().cookies }));
jest.doMock('next/navigation', () => {
const navigation = jest.requireActual('next/navigation');
redirect = jest.fn(navigation.redirect);
return {
...navigation,
redirect
};
});
});

test('basic with params', async () => {
const instance = initAuth0(withApi);
const handler = instance.withPageAuthRequired(
({ params }: { params: { lang: string; slug: string } }) =>
Promise.resolve(React.createElement('div', {}, `${params.lang}/${params.slug}`)),
{ returnTo: '/foo' }
);
expectTypeOf(handler).parameter(0).toMatchTypeOf<{ params: { lang: string } }>();
});

test('basic with search param', async () => {
const instance = initAuth0(withApi);
const handler = instance.withPageAuthRequired(
({ searchParams }: { searchParams: { limit: string | undefined } }) =>
Promise.resolve(React.createElement('div', {}, `${searchParams.limit}`)),
{ returnTo: '/foo' }
);
expectTypeOf(handler).parameter(0).toMatchTypeOf<{ searchParams: { limit: string | undefined } }>();
});

test('basic with params and search param', async () => {
const instance = initAuth0(withApi);
const handler = instance.withPageAuthRequired(
({
searchParams,
params: { lang }
}: {
params: { lang: string };
searchParams: { limit: string | undefined };
}) => Promise.resolve(React.createElement('div', {}, `${lang}${searchParams.limit}`)),
{ returnTo: ({ params, searchParams }) => `/foo/${params.lang}?limit=${searchParams.limit}` }
);
expectTypeOf(handler)
.parameter(0)
.toMatchTypeOf<{ params: { lang: string }; searchParams: { limit: string | undefined } }>();
});
});

describe('app route', () => {
let redirect: jest.Mock;

Expand Down
Loading