workos / authkit-nextjs

The WorkOS library for Next.js provides convenient helpers for authentication and session management using WorkOS & AuthKit with Next.js.
MIT License
43 stars 9 forks source link

Post login redirect taking me to 0.0.0.0:3000 #37

Open elliotcw opened 2 months ago

elliotcw commented 2 months ago

After signing in with WorkOS I am redirected to 0.0.0.0:3000.

Our deployed Next.js application is built and runs in a docker container. We run the container using Google Cloud Run. It looks like the authkit-nextjs middleware is using the request.nextUrl when handling the auth callback.

My suspicion is request.nextUrl is resolving to an internal address, 0.0.0.0:3000.

Our docker container has the following set:

EXPOSE 3000

ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"

# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD ["node", "apps/example-app/server.js"]

Is there a way to override this behaviour. Any pointers to how I can deploy my next.js application in docker and have workos redirects work correctly?

elliotcw commented 2 months ago

I was able to work around it using the Host header, based on this solution https://github.com/vercel/next.js/issues/37536#issuecomment-1157000990

Adding it to the middleware though didnt work out. I needed to add it to the auth/callback route handler.

// app/auth/callback/route.tsx
import { handleAuth } from '@workos-inc/authkit-nextjs';

// Redirect the user to `/` after successful sign in
// The redirect can be customized: `handleAuth({ returnPathname: '/foo' })`
const handler = handleAuth();

export const GET = async (request) => {
  const { nextUrl, headers } = request;
  let { url } = request;
  nextUrl.host = headers.get('Host') ?? nextUrl.host;

  // clear the port if not localhost
  if (!nextUrl.host.includes('localhost')) {
    nextUrl.port = '';
  }

  url = nextUrl.href;

  return handler(request);
};
PaulAsjes commented 2 months ago

Glad you found a workaround! I'll take a look at trying to reproduce this in a docker container, although this is going to be lower on our priority list as there's a workaround.