#Response.cookies is not setting the cookie on the frontend

1 messages · Page 1 of 1 (latest)

chrome cloud
#
  @Post("local")
  @UseGuards(LocalAuthGuard)
  async localLogin(
    @Req() request: Request,
    @Res({ passthrough: true }) response: Response
  ) {
    const jwt = await this.authService.localLogin(request.body);
    response.cookie("access_token", jwt, {
      maxAge: 3600000,
      sameSite: true,
      //enable to secure with https
      secure: false,
    });
  }

I want to set the cookies in the browser through the response.
However, I this does not seem to work. Nothing happens.

Also if I remove response.send({}) it throws an error: Error: SyntaxError: Unexpected end of JSON input, as if it is expecting a response object. However according to the NestJs docs @Res({ passthrough: true }) allows you to only set the cookie.

jagged talon
chrome cloud
#

that doesnt make sense

#

plus it errors out when I do request.cookie()

#

so I tried to Postman it, and I do infact get a cookie in the response. However, when I try to make the request through the browser in my app, I dont see the cookie available in chrome

wraith basalt
#

Do you by chance run your front end on a different port? I think the samesite parametr blocks that in the browser

chrome cloud
#

frontend on 3101, backend on 3100

#

I solved the JSON error btw, My fetch request was expecting a JSON response, so I removed it

#

@wraith basalt I changed sameSite to false and "lax", neither worked

#

maybe its my fetch request thats fucking things up?

#
function handleLocalSignIn() {
    console.log("loginCredentials", loginCredentials);

    fetch("http://localhost:3100/api/auth/local", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(loginCredentials),
    })
      .then((data) => {
        console.log("Success:", data);
        // set userdata to redux state, JWT to cookies
      })
      .catch((error) => {
        console.error("Error:", error);
      });
    setOpen(false);
  }
jagged talon
chrome cloud
#
  @Get("google")
  @UseGuards(GoogleOauthGuard)
  async googleLogin(@Req() request: Request) {}

  @Get("google/redirect")
  @UseGuards(GoogleOauthGuard)
  async googleLoginRedirect(
    @Req() request: Request,
    @Res() response: Response
  ) {
    const jwt = await this.authService.googleLogin(request.user);
    response.cookie("access_token", jwt, {
      maxAge: 3600000,
      sameSite: true,
      //enable to secure with https
      secure: false,
    });

    response.redirect(process.env.FRONTEND_URL);
  }
#

this works

jagged talon
chrome cloud
#

I am using import * as cookieParser from "cookie-parser";

#

as well as ```js
app.use(
session({
name: user-session,
secret: "some-secret-example",
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // This will only work if you have https enabled!
maxAge: 60000, // 1 min
},
})
);

#

but I dont think im actually using sessions yet

#

like its imported but not actually used

#

from what I remember

jagged talon
chrome cloud
#

didnt work

jagged talon
#

and httpOnly: true
because otherwise clients can read them

chrome cloud
#

ahh also I have this

#
app.use(passport.initialize());
  app.use(passport.session());
#

heres all of it

#
async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.setGlobalPrefix("api");

  app.use(cookieParser());

  app.enableCors({
    //origin: [config.get('CORS')],
    origin: "http://localhost:3101",
    credentials: true,
  });

  app.use(
    session({
      name: `user-session`,
      secret: "some-secret-example",
      resave: false,
      saveUninitialized: false,
      cookie: {
        sameSite: true,
        secure: false, // This will only work if you have https enabled!
        maxAge: 60000, // 1 min
      },
    })
  );

  app.use(passport.initialize());
  app.use(passport.session());

  const config = new DocumentBuilder()
    .setTitle("Construction Contracting")
    .setDescription("The MVP project API description")
    .setVersion("1.0")
    .addTag("mvp project")
    .addOAuth2()
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("docs", app, document);

  const port = process.env.PORT as string;
  //const port = this.configService.get("PORT");
  await app.listen(port, () => console.log(`Listening on port ${port}`));
}
bootstrap();

jagged talon
chrome cloud
#

also btw google works like its supposed to

#

now im working on my local login

#

with username/password, whereby the authorization is done in my API

#

its been some time since I've worked on this part of my project, but if I recall...

#

it was either I use express-session, or Redux

#

and I chose redux

#

but still had this stuff enabled

jagged talon
#

it strikes me odd app.use(cookieParser()); is used at the top
i remember vaguely it should be at the bottom (or it could be just me)

#

at least you can try shrugs

chrome cloud
#

moved it

#

didnt work

#

its really interesting that postman gets the cookie

#

but my app doesnt show it in google chrome

jagged talon
#

can you tell what your browser is saying, any cors errors maybe?

chrome cloud
#

im getting no errors

#

if I do res.send({access_token: JWT}) for example, I can get my JWT in the console

#

just doesnt get set to cookies, where its supposed to be

#

does there need to be a redirect or something?

#

only problem being that when I try to redirect from the backend, I get a cors error

#

even though I have cors enabled

jagged talon
#

odd

#

well i never set cookies my self
often use regular sessions shrugs
i avoid passport and their half baked docs

wraith basalt
#

You won't usually see cookies in the fetch response, look into the Storage (or Application) tab of the browser to see what cookies are there

#

Manually setting a cookie does not require any session at all btw, those are 2 completely separate things

chrome cloud
#

nope

#

its not in local, or session storage

#

and Ive read that the only place the JWT capabale of making protected endpoint requests, is in httpOnly cookies

jagged talon
chrome cloud
#

yah im looking there

#

none of those tabs has it, even after refreshing the page

jagged talon
chrome cloud
#

you're on a different browser?

jagged talon
jagged talon
chrome cloud
#

yah Ive looked in that place too

#

nothing

#

none of that tabs

#

every single one, Ive looked through

#

but it should ultimately be in the cookies tab you pointed out

jagged talon
#

what is odd now i think about it
passport usually sets the cookies etc for you
why you need to set them even?

chrome cloud
#

uhh well

#

im going off of what the other login endpoints are doing, in a similar fashion (such as the Google Oauth endpoint)

#

but also, tutorials online like this medium article are saying im doing it right

jagged talon
#

blogs like these are usual crap and dont update unlike nest it self

it's like watchinga years old tutorial on youtube

chrome cloud
#

sure but they are the best thing I can rely on right now

#

and my common sense is telling me im on the right path

#

just some small detail in the code is holding it back

#

my gut feeling

#

oh also, ive been reading the nestjs doc

#

same stuff

#

quite literally exactly what im doing

#

so, since postman is showing it

jagged talon
#

you said you where using passport
how about this then?
https://docs.nestjs.com/recipes/passport#implementing-passport-strategies

chrome cloud
#

I believe it has something to do with the frontend then

chrome cloud
jagged talon
#

https://docs.nestjs.com/recipes/passport#implementing-passport-local

you are aware validate is a reserved name and you totally didn't rename it something esle?

chrome cloud
#

so just to rehash...

  function handleGoogleSignIn() {
    window.location.href = "http://localhost:3100/api/auth/google";
  }

  function handleLocalSignIn() {
    console.log("loginCredentials", loginCredentials);

    fetch("http://localhost:3100/api/auth/local", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(loginCredentials),
    })
      .then((data) => {
        console.log("Success:", data);
        // set userdata to redux state, JWT to cookies
      })
      .catch((error) => {
        console.error("Error:", error);
      });
    setOpen(false);
  }

When I make a login request for google, it works, all of it the way its supposed to. I get my JWT, and it is set to Redux state, which displays all my user data on the frontend

however, my local login endpoint is not.

#

so it could be the way im making the fetch request

#

perhaps im missing some header details or something=