axios / axios

Promise based HTTP client for the browser and node.js
https://axios-http.com
MIT License
105.64k stars 10.95k forks source link

Cookies set on development, but not on production #5689

Closed henriquedevelops closed 1 year ago

henriquedevelops commented 1 year ago

Describe the bug

2 Docker containers:

  1. Server: Express.JS REST API with JWT authentication.
  2. Client: Next.JS app that uses Axios to talk with the server.

I tested it on localhost with Docker Compose: Everything working fine (both Postman and the browser successfully store the token as a cookie to use on subsequent requests.).

I deployed it to Google Cloud Run (one service for each container). Everything working fine except that now only requests made through Postman are storing the token as a cookie.

The browser (the Next.JS app) no longer does the same, even though the request returns a successful response there is no token in the browser cookies.

I did some research, found a few similar problems, and the solutions usually involve setting up some CORS configurations, so I updated my code by adding these configurations, but the issue remains.

I am currently trying it like this:

Server-side:

export const login = async (req: Request, res: Response) => {

...

  const accessToken = jwt.sign({ username, id, isAdmin }, jwtSecret, {
    expiresIn: "12h",
  });

  res
    .status(200)
    .cookie("accessToken-Myapp", accessToken, {
      secure: true,
      sameSite: "none",
    })
    .end();
};
const app = express();

app.use(helmet());
app.use(
  rateLimit({
    max: 300,
    windowMs: 60 * 60 * 1000,
    message: "Please try again later!",
  })
);

const corsConfig = {
  origin: true,
  credentials: true,
  allowedHeaders: ["Content-Type", "Authorization"],
};

app.use(cors(corsConfig));
app.options("*", cors(corsConfig));

app.use(express.json());
app.use(cookieParser());
app.use("/images", express.static("images"));

app.get("/health", (_, res: Response) => res.sendStatus(200));
app.use("/api/v1/auth", authRouter);

Client-side:

import axios from "axios";

export default axios.create({
  baseURL: `https://my-cloud-run-server-container-address/api/v1/`,
  withCredentials: true,
});

To Reproduce

No response

Code snippet

No response

Expected behavior

No response

Axios Version

No response

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

No response

OS

No response

Additional Library Versions

No response

Additional context/Screenshots

No response

Bibooo25730 commented 1 year ago

https://github.com/Bibooo25730/recat/blob/main/nodeApp/router/user.js

This is my login code, you can take a look, I registered using my email address, I am from China, I use 163 email address, but it should be more or less the same