I’m currently developing a reservation system and the authentication I use is JWT and saving it in my cookie.This is how I send the cookie after the user login.
- React Login
const login = async () => {
const requestOptions = {
credentials: 'same-origin',
withCredentials: true,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
path: '/',
body: JSON.stringify({
id: "User ID",
password: "Password"
})
};
fetch('https://localhost:4000/auth/login', requestOptions)
.then(res => res.json())
.then(response => {
console.log('result login', response)
})
.catch((e) => {
console.log('[error] login', e)
})
// empty dependency array means this effect will only run once (like componentDidMount in classes)
};
useEffect(() => {
login()
}, []);
- Nest JS
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@UseGuards(LocalGuard)
@Post('login')
async login(
@Body() data: UserLoginDto,
@Res({ passthrough: true }) res: Response,
) {
console.log('[LOGIN]', data);
const access_token = this.authService.login(data);
res.cookie('access_token', access_token, {
httpOnly: true,
secure: true,
sameSite: 'none',
path: '/',
maxAge: 10000,
expires: new Date(Date.now() + 1 * 24 * 60 * 1000),
});
return access_token;
}
then I can see a cookie data like this.
However, It isn’t stored in my browser.
I’d tried credentials, https, httpOnly, Secure, sameSite, expires options. But these didn’t working and still get in.
Is there way to store cookie? Please help me.
Fix and New Error
I stored my cookie! But I got Cors error. I think access-control-allow-origin: * is problem. Therefore, I fixed my code like this
- Nest Js
app.enableCors({
origin: [
'https://127.0.0.1:3000',
'https://localhost:3000',
],
credentials: true,
// methods: ['GET', 'POST'],
// allowedHeaders: ['Content-Type', 'Authorization'],
// maxAge: 86400,
});
but ‘access-control-allow-origin’ isn’t changed.
How can I fix access-control-allow-origin?
2
Answers
I’m guessing this is your testing environment, so the React app is running on a different port than the Nest.js app, right?
Your Nest app needs to allow the React app’s origin for CORS. Add this to your main.ts:
Replace the port number with the port of your React app.
Further reading on CORS, if you’re interested: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Edit: After reading your cookie configuration again, it might also be an issue with those. It seems you’re running the app on localhost, but having
secure
set to true, which won’t work for a non-HTTPS environment. I’d suggest settingsecure
conditionally, depending on if the app is running locally or in production. Also thecredentials: 'same-origin'
configuration might not work for different ports.Why are you commenting out the methods allowed? To enable cors, you should specify the origins and the methods allowed. Uncomment the methods option and it should work: