question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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:

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Vadorequestcommented, Jun 21, 2021

This answer looks like what I was looking for.

https://github.com/auth0/nextjs-auth0/issues/108#issuecomment-800059278

1reaction
Vadorequestcommented, Jun 18, 2021

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Generated URLs – Vercel Docs
To customize the appearance of any of the generated URLs mentioned above, you can enable the Preview Deployment Suffix feature available in the...
Read more >
How do I set up a staging environment on Vercel?
You can add a domain by clicking the "Settings" tab from a Project and selecting the Domains section. From the Domains section, you...
Read more >
REST API – Vercel Docs
Go to the drop-down menu in your Personal Account at the top-left in the Navigation bar and click Settings. Navigate to the Tokens...
Read more >
Environment Variables – Vercel Docs
Environment Variables are key-value pairs configured outside your source code so that each value can change depending on the Environment.
Read more >
Domains – Vercel Docs
When you buy a domain through Vercel, we configure and set the nameservers, which means you do not need to set any DNS...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found