I'm currently working on a project using next.js for the frontend and nest.js for the backend. Despite having CORS enabled in my main.ts
file of nest.js, I keep encountering CORS errors.
Below is an excerpt from my main.ts file:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import cookieParser from 'cookie-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
if (process.env.APP_ENV !== 'production') {
app.enableCors({
allowedHeaders: '*',
origin: '*',
credentials: true,
});
} else {
app.enableCors({
origin: process.env.FE_URL,
credentials: true,
});
}
app.use(cookieParser());
await app.listen(process.env.PORT || 5000);
}
bootstrap();
I have also attempted the following solutions:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import cookieParser from 'cookie-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
allowedHeaders: '*',
origin: '*',
credentials: true,
});
app.use(cookieParser());
await app.listen(process.env.PORT || 5000);
}
bootstrap();
Additionally, I tried:
app.enableCors({
origin: 'http://localhost:3000',
credentials: true,
});
In my _app.js
frontend file, I've set Axios global configurations as follows:
axios.defaults.baseURL = 'http://localhost:5000';
axios.defaults.withCredentials = true;
When making a request to the nest.js application in my login.tsx
file, like so:
const { data } = await axios.post('/auth/login', values);
The 'values' object contains username and password fields. However, despite trying various solutions found on StackOverflow, the issue persists. This setup was functional just a few days ago, and I'm unsure of what has changed.
If you can offer any guidance or require additional code snippets, please let me know. Thank you!