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

How to configure baseUrl when using Vercel preview environment, to stay on the same domain? #420

Closed
Vadorequest opened this issue Jun 18, 2021 · 8 comments
Labels
question Further information is requested

Comments

@Vadorequest
Copy link

Description

In production and in preview environments, we configured Vercel AUTH0_BASE_URL=VERCEL_URL env var. It works fine in production, but on preview it changes the domain, because VERCEL_URL doesn't use a custom domain name but the domain dynamically generated for the deployment.

We're not using initAuth0 in the app and we rely on the AUTH0_BASE_URL, but I believe we need to make an exception in the preview environment by detecting the current domain and configure Auth0 to redirect to that same domain after being authenticated.

I tried to adapt our [...auth0].ts file to handle that edge case, but it didn't seem to work as I get TypeError: "baseURL" is required. (I've disabled AUTH0_BASE_URL for the Vercel preview environment)

Reproduction

HomeScreen.tsx

export function HomeScreen() {
  const {role, handleRoleChange} = useHomeScreen();
  const hostname =
    typeof window !== 'undefined' ? window?.location?.hostname : '';

  return (
    <Layout>
      <a href={`/api/auth/login?role=${role}&hostname=${hostname}`}>
        <button disabled={!role}>Login</button>
      </a>
    </Layout>
  );
}

[...auth0.ts]

export default handleAuth({
  async login(req, res) {
    try {
      const previewEnvBaseUrl =
        process.env.VERCEL_ENV === 'preview'
          ? `https://${req?.query?.hostname}` || ''
          : '';
      const ADMIN_USER_ROLES = [USER_ROLES.SPOTTED_OWNER, USER_ROLES.SPOTTED];
      const returnToPath = ADMIN_USER_ROLES.includes(req.query.role as string)
        ? ADMINROUTES.HOME
        : '/profile';
      console.log('previewEnvBaseUrl', previewEnvBaseUrl);
      console.log('returnToPath', returnToPath);

      initAuth0({
        baseURL: previewEnvBaseUrl, // This doesn't seem to set "baseURL"
      });

      await handleLogin(req, res, {
        returnTo: returnToPath,
        authorizationParams: {
          role: req.query.role,
        },
      });
    } catch (error) {
      res.status(error.status || 500).end(error.message);
    }
  },
  async callback(req, res) {
    try {
      await handleCallback(req, res, {afterCallback});
    } catch (error) {
      res.status(error.status || 500).end(error.message);
    }
  },
  async logout(req, res) {
    try {
      res.setHeader('Set-Cookie', [
        'internalId=deleted; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT',
        'role=deleted; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT',
        'key=deleted; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT',
      ]);
      await handleLogout(req, res);
    } catch (error) {
      res.status(error.status || 500).end(error.message);
    }
  },
});

I assumed using initAuth0 and providing a baseURL value would work.

      initAuth0({
        baseURL: previewEnvBaseUrl,
      });

I'm a bit confused by how handleAuth HOC works and I might not be doing things correctly. The previewEnvBaseUrl contains the expected value, so the issue lies in how to configure Auth0 to use the proper domain.

Environment

Please provide the following:

  • Version of this library used: "@auth0/nextjs-auth0": "^1.3.0"
@adamjmcgrath
Copy link
Contributor

Hey @Vadorequest

When instantiating the SDK you can either use the named exports (eg, handleAuth) and we create a instance of the SDK for you, or you create an instance yourself const auth0 = initAuth0(); auth0.handleAuth(); (more info here). So you can't use them together, eg:

export default handleAuth({ // Creates an instance of the SDK
  async login(req, res) {
    initAuth() // Creates another instance of the SDK

You're getting TypeError: "baseURL" is required because handleAuth is trying to create an instance of the SDK, but you haven't specified the baseUrl env var.

You could lazily create an insance of the SDK on the first request, eg

let instance;
export default (req, res) {
  ...
  instance = instance || initAuth0({ baseURL: previewEnvBaseUrl });
  return instance.handleAuth(...)(req, res);
};

But there is probably a better solution around figuring out the url at build or boot time - is there no way you can derive the preview url from VERCEL_URL? What is a typical value for VERCEL_URL for a preview deploy and what is a typical value for previewEnvBaseUrl?

@adamjmcgrath adamjmcgrath added the question Further information is requested label Jun 18, 2021
@Vadorequest
Copy link
Author

But there is probably a better solution around figuring out the url at build or boot time - is there no way you can derive the preview url from VERCEL_URL? What is a typical value for VERCEL_URL for a preview deploy and what is a typical value for previewEnvBaseUrl?

I don't believe that's possible. That's because when using custom domain (eg: domain name based on the git branch), it redirects from something like git-fix-auth0.vercel.app to ai7826jdsjs.vercel.app). The VERCEL_URL is ai7826jdsjs.vercel.app.

This is an issue that's bound to happen with any website that has several domains attached to it, I need the user to stay on the same domain.

@adamjmcgrath
Copy link
Contributor

This is an issue that's bound to happen with any website that has several domains attached to it, I need the user to stay on the same domain.

I'm confused - what do you want the baseUrl to be in your example? git-fix-auth0.vercel.app? If so, could you not construct that from ${VERCEL_GIT_COMMIT_REF}.vercel.app?

@Vadorequest
Copy link
Author

Vadorequest commented Jun 18, 2021 via email

@Vadorequest
Copy link
Author

Vadorequest commented Jun 18, 2021 via email

@Vadorequest
Copy link
Author

This answer looks like what I was looking for.

#108 (comment)

@adamjmcgrath
Copy link
Contributor

@Vadorequest - yep, if you don't know the URL until request time - then that would work

Closing this - feel free to ping me if oyu'd like to discuss further

@ADTC
Copy link
Contributor

ADTC commented Jan 24, 2024

Worth noting what's here on this example page. (You can skip modding the build command and output directory.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants