3000 / 8888 Port Conflict with Netlify Dev and Nextauth on Localhost

Using Netlify dev locally as I wish to test my serverless functions locally.

Integrated next-auth recently and running into this issue.

On production all is fine in the world. Serverless functions work, next-auth works, all good.

In my .env.local file I use

NEXTAUTH_URL=http://localhost:8888

However doing so means the next-auth callback does not work. Testing a test login gets me a

“Function not found…” error, and in the netlify dev logs:

Warning: Missing form submission function handler
Request from ::1: POST /api/auth/callback/credentials/index.html

A workaround is to swap the NEXT_URL to

NEXTAUTH_URL=http://localhost:3000

This works but it basically means after login it’s swapping me to port 3000 where my serverless functions wont work locally. This isnt ideal and I would imagine if there is functionality then intertwining serverless functions and next-auth this will become a headache to test locally.

I have tried another workaround in my Netlify.toml file to attempt to redirect the /api/ function next-auth uses with:

[dev]
  command = "npm run dev"
  port = 8888
  publish = "out"
  targetPort = 3000

[[redirects]]
  from = "/api/*"
  to = "http://localhost:3000/api/:splat"
  status = 200
  force = true

This worked locally where I was then able to use port 8888 for everything (serverless functions and next-auth all worked) but this borked production and for some reason when I go to https://www.mysite.com/api/auth/signin I get a HTTP Error 505 (I had hoped this toml redirect would only work on local since I used [dev] but perhaps I’m getting something wrong there.

Really I would just love this to work locally and on production.

Any ideas how I could get this to work?

Ive just realised also the redirect solution (if I could figure out how to get this working on only localhost) wouldnt work either as this does the same thing, redirecting to 3000 after next-auth login, meaning then I’m on the “wrong” port (3000 not 8888) and therefore netlify serverless functions wont work.

Any ideas where I am going wrong?

Would appreciate some help with this!

Next Auth is widely used by a lot of users and no one has compained about this, thus far. Something must be definitely wrong with the configuration here.

Could you make sure Next.js Runtime is running when you run Netlify CLI? Could you share the CLI version and the logs when you run netlify dev?

Hi. Appreciate the reply but would like this solving its causing a lot of grief as I need next-auth running simultaneously on localhost with netlify dev.

In this post in July 2021 Dev environment starting servers on both :3000 and :8888

You stated

" That’s how it works! :3000 is the one started by your SSG. :8888 is the one started by Netlify Dev. Netlify-specific features like Functions won’t work on :3000 ."

This seems to align with the issue I have, eg I would like to have netlify functions working together with Netlify Dev on the same port.

Is this feasible?

RE your questions my set up is:

netlify --version
netlify-cli/15.5.0 darwin-x64 node-v18.16.0

Here is my log when running Netlify Dev:

  • Executing task: netlify dev
◈ Netlify Dev ◈
◈ Ignored general context env var: LANG (defined in process)
◈ Injected .env.local file env var: FAUNADB_SERVER_SECRET
◈ Injected .env.local file env var: NEXTAUTH_URL
◈ Injected .env.local file env var: NEXTAUTH_SECRET
◈ Injected .env.local file env var: FACEBOOK_CLIENT_ID
◈ Injected .env.local file env var: FACEBOOK_CLIENT_SECRET
◈ Setting up local development server
◈ Starting Netlify Dev with Next.js

> nameofmysite@2.0.0 dev
> next dev

- ready started server on 0.0.0.0:3000, url: http://localhost:3000
✔ Waiting for framework port 3000. This can be configured using the 'targetPort' property in the netlify.toml
◈ Loaded function function1 http://localhost:8888/.netlify/functions/function1.
◈ Loaded function function2 http://localhost:8888/.netlify/functions/function2.
◈ Functions server is listening on 56323
- info Loaded env from (mypath)-nextjs/.env.local

   ┌─────────────────────────────────────────────────┐
   │                                                 │
   │   ◈ Server now ready on http://localhost:8888   │
   │                                                 │
   └─────────────────────────────────────────────────┘

◈ Loaded edge function netlify dev handler
- event compiled client and server successfully in 204 ms (18 modules)
- wait compiling / (client and server)...
- wait compiling /api/auth/[...nextauth] (client and server)...
- wait compiling /_error (client and server)...
- event compiled client and server successfully in 721 ms (422 modules)
- warn Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload
DEBUG_ENABLED 0 [ 'DEBUG_ENABLED' ]

Not possible. They’re always going to run on two separate ports. As I mentioned, a lot of other users are using this setup. I still don’t understand how this is a problem though. Any requests from :8888 should be handled on the same port.

Can you share a minimal reproduction of your example that’s causing issues?

Thank you for the reply.

My issue is as follows.

When developing locally, I use a mix of netlify serverless functions together with functionality that uses next-auth (for logging in).

When testing on localhost, its a pain to properly test when I need to manually swap ports between 3000 and 8888.

So a workaround I found so far was to use:

[dev]
  command = "npm run dev"
  port = 8888
  publish = "out"
  targetPort = 3000

[[redirects]]
  from = "/api/*"
  to = "http://localhost:3000/api/:splat"
  status = 200
  force = true

In my netlify.toml file.

Locally using this approach I seem to be able to use my serverless functions but also have next-auth functionality work all on one port (8888).

However, when I deploy to production this breaks my production site. So what I end up doing is before each deploy in VS code I manually comment out the redirect in the netlify.toml, deploy, then manually uncomment it.

This works but is super time consuming and I’m pretty sure I’m not doing this in the optimal way.

Is there a way to:

  1. Only apply that redirect above locally so when it gets deployed to production it essentially doesnt do anything?

or

  1. A use a different way of handling this eg using Ive seen a proxy server can be used but a bit out of my depth on figuring out how to set that up.

or

  1. Automate that process of always ensuring that redirect above never gets deployed to production (seems a bit hacky but it would serve the purpose I think and mean I wouldnt have to keep doing this manually on each deploy which is slowing things down a lot).

… Or another way I’m missing here?

I hope that clarifies my issue a bit, thanks ahead for any suggestions you can give.

While your post is fairly detailed (thank you for that, it’s hard to find such great posts!), unfortunately, this is not a case of me having troubles to understand you. I have understood your issue fairly well, but what I was looking for is a piece of code (ideall, a repo) that I can test and see what could be causing issues. As mentioned before, you’re the only one that has encoutered this issue, so something specific to your setup could be causing this. Unfortunately, I’ve never tried this before (I am not a Next.js fan/user), so I don’t know for sure if it works or not. I’m just basing my reply on the fact that I have seen a lot of users use next-auth, but none of them (at least no one that I recall) has mentioned this issue.

Due to the nature of this problem, any amount of textual explanation would unfortunately not work. I need to see the repo that’s causing this issue to comment further. I can possibly setup one myself, but that has 2 downsides:

  1. There are a lot more users waiting for a response. So instead of trying to setup a reproduction myself, I can answer those users, while you provide me something to debug
  2. The default setup might work as expected, which would bring us again to the point of you having to share your repo for further investigation

Thanks for reply.

I will PM you with repo access so you can take a look.

Ive given you access now.

In summary what I’m trying to achieve is an automated frictionless way to ensure that I can run nextauth (using 3000) at the same time as using port 8888 so i can use netlify dev serverless functions locally.

Theres no issue on production this gets handled, but locally I currently apply a “hack” to use

[dev]
  command = "npm run dev"
  port = 8888
  publish = "out"
  targetPort = 3000

[[redirects]]
  from = "/api/*"
  to = "http://localhost:3000/api/:splat"
  status = 200
  force = true

In my netlify.toml file.

Then every time I deploy in VS code I manually have to remember to discard changes on that file before it goes to production. To my knowledge there is no way to have a local netlify.toml file so this is the best way I have found that works so far but its very cumbersome.

Ideal fix would be:

  1. A set up locally where port redirects work so that 8888 and 3000 work together whereby deploying those files to production didnt break anything.

  2. The “hack” above in which case I need a more automated way to ensure those changes only stay local. I tried using .gitignore for this but a but new to this and didnt manage to get that working.

Thanks ahead really appreciate it.

Thanks. I tried your repo, but how exactly do I trigger the next auth stuff? I don’t see any login area on your website.

Sure so the default next-auth login would work I think to test the next-auth side of things, should be on localhost:3000/api/auth/signin

This only uses the nextauth (3000) port, so would work. Its when I need both ports working simultaneously when I have the issue (eg next-auth functionality that accesses a serverless function). I can try find an example of a flow that does that but it shouldn’t really be necessary I would think?

Thank you for that. I tried it and the first issue I noticed, there was no NEXTAUTH_URL environment variable being set. I don’t know if you had an .env file locally that had this variable, but since I did not have it, my login request from localhost:8888 was being redirected to localhost:3000 once I login. I solved that by adding the above environment variable with the value http://localhost:8888.

Once that was solved, I was getting an error saying Function not found on the callback URL (http://localhost:8888/api/auth/callback/credentials) once I logged in. I then compared this with our NextAuth example: next-runtime/demos/next-auth at main · netlify/next-runtime (github.com). The only thing I did was simplify your code to just one (Credentials) provider. Your current code being stripped to:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: {
          label: "Email",
          type: "email",
          placeholder: "jsmith@m.com",
        },
        password: { label: "Password", type: "password" },
      },
      authorize: async (credentials) => {
        if (
          credentials.username === "jsmith@m.com" &&
          credentials.password === "password"
        ) {
          const user = {
            fullName: "John Smith",
            email: "jsmith@m.com",
          };
          return Promise.resolve(user);
        } else {
          return Promise.resolve(null);
        }
      },
    })
  ],
  events: {
    signIn: async ({ user, account, profile }) => {
      console.log("User:", user);
    },
  },
});

and the netlify.toml just being:

[[plugins]]
  package = "@netlify/plugin-nextjs"

it works fine. I get this in the console:

User: { fullName: 'John Smith', email: 'jsmith@m.com' }
API handler should not return a value, received object.

If this is not working in the more complicated setup, it would be hard to provide code-level debugging.

Thanks a lot for this.

So yes my NEXTAUTH_URL is set as an environmental variable on my side in Netlify, and I load it in env.local.

On my .env.local file I use:

# NextAuth Credentials
NEXTAUTH_URL=http://localhost:3000

On my netlify environmental variable I use:

Theres a weird conflict here between my netlify env variable in the web interface for local development (netlify CLI), as 8888 and then my local .env.local file as 3000 (which if I’m not taken will take priority here).

Should the NEXT_AUTH URL for local development point to 8888 or 3000?

Hopefully its a case of just setting this correctly, but if not I will try to isolate a more simple case for you to test if this still doesnt work.

Yes, the NEXTAUTH_URL should be :8888 as that’s where you expect it to work.

Thanks I’ll see the the issue comes up again adjusted to 8888.

So with that set up changing .env.local with NEXTAUTH_URL=http://localhost:8888 ( I still get a world of pain…

Smaller but annoying issue…

If I go to some next-auth functionality eg sign out (the default page being http://localhost:8888/api/auth/signout) then sign out, next-auth redirects me back to http://localhost:3000/ after signing out.

Similarly if I sign in eg going to http://localhost:8888/api/auth/signin (right now the repo is set to use next-auth EmailProvider with a magic link so this should be testable at the moment) it will also redirect me back to (in this case) http://localhost:3000/api/auth/verify-request?provider=email&type=email

So I end up back at 3000 again, where my serverless functions wont work.

I then have to remember to keep swapping the ports back manually to 8888 which is a little time consuming when testing things locally, but the bigger issue I have is if on this redirected page a serverless function is required to do something its not going to work (i ran into this before but forget the example use case).

Is this normal behaviour and do people normally have to go manually swapping ports back and forwards like this? What if they have serverless functions that need to be used directly after such a login or next-auth feature?

I would think there would be a way to handle the redirections better somehow but its way above my head.

Bigger issue

So my next-auth functionality on the above set up totally breaks on production. If I go to mysite.com/api/auth/signin for example I get a 500 error and none of the next-auth pages load.

Any ideas where this is all going wrong?

Sorry my mistake on above, I had mistakenly left that netlify.toml redirect on production when deploying so thats why production broke.

To clarify Bigger Issue was a non issue. Production has always worked fine and of course works fine with this change since its simply changing the local env.local file so nothing is actually changing there.

Smaller but annoying issue still remains (eg next-auth locally redirecting me away from 8888 when I use any of its functionality which will take me to a place where serverless functions wont work).

Sorry for the messy reply here, just tested again and realised localhost also was affected by me leaving that netlify.toml redirect hack on. With that turned off and NEXTAUTH_URL=http://localhost:8888 set in .env.local actually I get errors when I try to sign in or out using the basic EmailProviders login eg at

http://localhost:8888/api/auth/signin (signing in gets me a function not found error)

http://localhost:8888/api/auth/signout signing out also gets the same error:

Warning: Missing form submission function handler
Request from ::1: POST /api/auth/signout

Yes, I was getting a similar issue, but that got solved when I removed all of your code and just kept the part I have shared above. Can you try with that?