Repository: auth0/nextjs-auth0
Pull request #255 (2021-01-25 15:18:24)

[SDK-2259] Remove env var dependency at build time
### Description

Because of [static generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) `withPageAuthRequired` is called at build time. We need to move the dependency `withPageAuthRequired` has on the server instance to be at runtime, so that you don't need to specify environment variables to configure the SDK at build time

### References

fixes: #154 

### Testing

- [x] This change adds test coverage for new/changed/fixed functionality

### Checklist

- [x] I have added documentation for new/changed functionality in this PR or in auth0.com/docs
- [x] All active GitHub checks for tests, formatting, and security are passing
- [x] The correct base branch is being used, if not `master`



Patch:
diff --git a/src/helpers/with-page-auth-required.ts b/src/helpers/with-page-auth-required.ts
index 4ce73a3a..9e0063be 100644
--- a/src/helpers/with-page-auth-required.ts
+++ b/src/helpers/with-page-auth-required.ts
@@ -1,5 +1,5 @@
 import { GetServerSideProps, GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
-import { Claims, Session, SessionCache } from '../session';
+import { Claims, GetSession } from '../session';
 import { assertCtx } from '../utils/assert';
 import React, { ComponentType } from 'react';
 import { WithPageAuthRequiredOptions as WithPageAuthRequiredCSROptions } from '../frontend/with-page-auth-required';
@@ -90,7 +90,7 @@ export type WithPageAuthRequired = {
 /**
  * @ignore
  */
-export default function withPageAuthRequiredFactory(sessionCache: SessionCache): WithPageAuthRequired {
+export default function withPageAuthRequiredFactory(getSession: GetSession): WithPageAuthRequired {
   return (
     optsOrComponent: WithPageAuthRequiredOptions | ComponentType = {},
     csrOpts?: WithPageAuthRequiredCSROptions
@@ -101,13 +101,13 @@ export default function withPageAuthRequiredFactory(sessionCache: SessionCache):
     const { getServerSideProps, loginUrl = '/api/auth/login' } = optsOrComponent;
     return async (ctx: GetServerSidePropsContext): Promise<GetServerSidePropsResultWithSession> => {
       assertCtx(ctx);
-      if (!sessionCache.isAuthenticated(ctx.req, ctx.res)) {
+      const session = getSession(ctx.req, ctx.res);
+      if (!session?.user) {
         // 10 - redirect
         // 9.5.4 - unstable_redirect
         // 9.4 - res.setHeaders
         return { redirect: { destination: `${loginUrl}?returnTo=${ctx.resolvedUrl}`, permanent: false } };
       }
-      const session = sessionCache.get(ctx.req, ctx.res) as Session;
       let ret: any = { props: {} };
       if (getServerSideProps) {
         ret = await getServerSideProps(ctx);
diff --git a/src/index.ts b/src/index.ts
index 106f3fd6..2fbec184 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -61,7 +61,7 @@ export const initAuth0: InitAuth0 = (params) => {
   const getSession = sessionFactory(sessionCache);
   const getAccessToken = accessTokenFactory(getClient, config, sessionCache);
   const withApiAuthRequired = withApiAuthRequiredFactory(sessionCache);
-  const withPageAuthRequired = withPageAuthRequiredFactory(sessionCache);
+  const withPageAuthRequired = withPageAuthRequiredFactory(getSession);
   const handleLogin = loginHandler(config, getClient, transientStore);
   const handleLogout = logoutHandler(config, getClient, sessionCache);
   const handleCallback = callbackHandler(config, getClient, sessionCache, transientStore);
@@ -85,7 +85,7 @@ export const getSession: GetSession = (...args) => getInstance().getSession(...a
 export const getAccessToken: GetAccessToken = (...args) => getInstance().getAccessToken(...args);
 export const withApiAuthRequired: WithApiAuthRequired = (...args) => getInstance().withApiAuthRequired(...args);
 export const withPageAuthRequired: WithPageAuthRequired = (...args: any[]): any =>
-  getInstance().withPageAuthRequired(...args);
+  withPageAuthRequiredFactory(getSession)(...args);
 export const handleLogin: HandleLogin = (...args) => getInstance().handleLogin(...args);
 export const handleLogout: HandleLogout = (...args) => getInstance().handleLogout(...args);
 export const handleCallback: HandleCallback = (...args) => getInstance().handleCallback(...args);


Test patch:
diff --git a/tests/index.test.ts b/tests/index.test.ts
new file mode 100644
index 00000000..e8b8026c
--- /dev/null
+++ b/tests/index.test.ts
@@ -0,0 +1,11 @@
+import { withPageAuthRequired, withApiAuthRequired } from '../src';
+
+describe('index', () => {
+  test('withPageAuthRequired should not create an SDK instance at build time', () => {
+    const secret = process.env.AUTH0_SECRET;
+    delete process.env.AUTH0_SECRET;
+    expect(() => withApiAuthRequired(jest.fn())).toThrow('"secret" is required');
+    expect(() => withPageAuthRequired()).not.toThrow();
+    process.env.AUTH0_SECRET = secret;
+  });
+});