Next.js Discord

Discord Forum

How to store cookies on the client from nextresponse

Answered
Basset Bleu de Gascogne posted this in #help-forum
Open in Discord
Basset Bleu de GascogneOP
import { NextRequest, NextResponse } from "next/server";
import { compareSync } from "bcrypt-ts";
import { USERPROFILE } from "@/app/types/profile.type";

export async function GET(request:NextRequest){
    await console.log("Get", request);
    return NextResponse.json({
        "message":"Verified"
    });
}

export async function POST(request:NextRequest){
    // const body:USERPROFILE = await request.json();
    const body = await request.text();
    console.log(body);
    const hash = "value"
    // const result:boolean = compareSync(body.password?.password!,hash)
    const result = true 
    if(result === true){
        let response = NextResponse.next();
        response.cookies.set("sessionkey","generatedvalue",{
            path:"/login",
            expires:Date.now() + 1000
        })
        console.log(response)
        return  NextResponse.json({success:"Successfully loged in"},{status:200})
    }
    else{
        return NextResponse.json({error:"Error logging"},{status:400})
    }

    
   
} 

Here is the code for the api route I am creating.
Answered by B33fb0n3
the client itself automatically saves it. You can access it via muliple npm librarys. Do you need an examples for a npm library? @Basset Bleu de Gascogne
View full answer

96 Replies

Basset Bleu de GascogneOP
Here is the response
NextResponse [Response] {
  [Symbol(realm)]: { settingsObject: {} },
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: false,
    requestIncludesCredentials: false,
    type: 'default',
    status: 200,
    timingInfo: null,
    cacheState: '',
    statusText: '',
    headersList: _HeadersList {
      cookies: [Array],
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    },
    urlList: []
  },
  [Symbol(headers)]: _HeadersList {
    cookies: [
      'sessionkey=generatedvalue; Path=/login; Expires=Wed, 29 Nov 2023 20:12:41 GMT'
    ],
    [Symbol(headers map)]: Map(2) {
      'x-middleware-next' => [Object],
      'set-cookie' => [Object]
    },
    [Symbol(headers map sorted)]: null
  },
  [Symbol(internal response)]: {
    cookies: ResponseCookies { _parsed: [Map], _headers: [_HeadersList] },
    url: undefined
  }
1.I can see that the response does contain my cookies but I can see it in the postman cookies tab
2. Also how do i access it in the client side and store it
the client itself automatically saves it. You can access it via muliple npm librarys. Do you need an examples for a npm library? @Basset Bleu de Gascogne
Answer
If the client automatically saves it I can use it to send the cookies each time my user shifts from one segment route to another and see if the session hasnt expired
But I am not able to see the cookies in the postman tab
@Basset Bleu de Gascogne would be great to know as
when I want to get cookies I use this library: https://www.npmjs.com/package/cookies-next
@B33fb0n3 when I want to get cookies I use this library: https://www.npmjs.com/package/cookies-next
Basset Bleu de GascogneOP
Amazing typescript enabled ?
@B33fb0n3 yes, you can do that inside your middleware
Basset Bleu de GascogneOP
great! but I would also be sharing hte cookie back and forth to check if it hasnt expired right
with the database
now that I type I also mention the expire field with it , does that mean it gets deleted once the expiry is reached ?
yes, you can also do that inside the middleware
@B33fb0n3 yes, you can also do that inside the middleware
Basset Bleu de GascogneOP
do which part ?
@B33fb0n3 this one: https://discord.com/channels/752553802359505017/1179515912471195678/1179517213426860032
Basset Bleu de GascogneOP
Check if the cookie has expired in middleware
interesting
thanks any clue why cant I see the cookie in postman tab
you don't need to check that. If they expired, they won't be send from client to server
@B33fb0n3 you don't need to check that. If they expired, they won't be send from client to server
Basset Bleu de GascogneOP
gotcha. But I would also be storing it in the db
@B33fb0n3 you don't need to check that. If they expired, they won't be send from client to server
Basset Bleu de GascogneOP
But are you sure the above code is sending the cookies alogn with the custom response I have
@B33fb0n3 this one: https://discord.com/channels/752553802359505017/1179515912471195678/1179517213426860032
Basset Bleu de GascogneOP
Hi I dont see the cookies in my brower set
@Basset Bleu de Gascogne Hi I dont see the cookies in my brower set
you can see them inside your cookies tab
@B33fb0n3 you can see them inside your cookies tab
Basset Bleu de GascogneOP
Ya its not there
@B33fb0n3 if you ask for them, yeah
Basset Bleu de GascogneOP
wdym ask for them ?
This is hte code
where I get the response
it seems like a login page 🤔
@B33fb0n3 it seems like a login page 🤔
Basset Bleu de GascogneOP
yes its a login page
this might help
put everythign at one place
do I miss something or why do you need cookies there? 🤔
*clientside
@B33fb0n3 do I miss something or why do you need cookies there? 🤔
Basset Bleu de GascogneOP
I am creating a cookie in the server side
And storing it in clients browser
Then using that I can do two things use it in middleware
And also verify that value to the database value to match that the user is valid and has permission to the page
@Basset Bleu de Gascogne And also verify that value to the database value to match that the user is valid and has permission to the page
yea. But why in while logging in? You don't need them there clientside. You just set them to the client. Then whenever you navigate (the middleware will be executes), you are able to get the cookies through the request. You can verify it with the database and easy auth
Whats the best way to do this ?
@Basset Bleu de Gascogne Whats the best way to do this ?
then you are doing it right. Create a api route and return the token as cookie. Then create a middleware, that verify this token on each request for protected routes
I created this as my api route
import { NextRequest, NextResponse } from "next/server";
import { compareSync } from "bcrypt-ts";
import { USERPROFILE } from "@/app/types/profile.type";

export async function GET(request:NextRequest){
    await console.log("Get", request);
    return NextResponse.json({
        "message":"Verified"
    });
}

export async function POST(request:NextRequest){
    const body:USERPROFILE = await request.json();
    // const body = await request.text();
    console.log(body.password?.password);
    const hash = "value"
    // const result:boolean = compareSync(body.password?.password!,hash)
    const result = true 
    if(result === true){
        let response = NextResponse.next();
        response.cookies.set("sessionkey","generatedvalue",{
            expires:Date.now() + 100000
        })
        console.log(response)
        return  response
    }
    else{
        return NextResponse.json({error:"Error logging"},{status:400})
    }

    
   
}
this is hte code
NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler but I get this error
@Basset Bleu de Gascogne token ?
yea token
Basset Bleu de GascogneOP
const token = await jwt.sign(tokenData, process.env.TOKEN_SECRET!, {expiresIn: "1d"}) something like this you mean right ?
the token is not just a random generated value. It's basically the key to autorize every request from the user
Basset Bleu de GascogneOP
but isnt jwt different to cookies
got it I was able to get the cookie
but I want to understand now the difference between using jwt and nornmally setting up the cookie
able to get it even in postman
Thanks for your help
@Basset Bleu de Gascogne got it I was able to get the cookie
exactly that should be the right behavior ^^
@Basset Bleu de Gascogne but I want to understand now the difference between using jwt and nornmally setting up the cookie
a normal cookie is just a little thing that safe some data in the client browser. A jwt is a token, which can be used to valide it and to grant different auth functionality
@Basset Bleu de Gascogne but I want to understand now the difference between using jwt and nornmally setting up the cookie
cookies, even with httpOnly can still be hijacked and their content read and changed.
JWTs however, are signed therefore it can be guaranteed that it can't be tampered.
@aardani cookies, even with httpOnly can still be hijacked and their content read and changed. JWTs however, are signed therefore it can be guaranteed that it can't be tampered.
Basset Bleu de GascogneOP
Oh okay when you say signed , what do you mean by that ? Like I create a token I use this jwttokenlibrary and sign it what does that mean and why is it impossible for that too be manipulated
@Basset Bleu de Gascogne Oh okay when you say signed , what do you mean by that ? Like I create a token I use this jwttokenlibrary and sign it what does that mean and why is it impossible for that too be manipulated
all JWT are signed by default, its how jwt works fundamentally. if you edit the jwt, it becomes invalid.
signing is the process of taking a payload and a hashing algorithm to make it so that its impossible to be manipulated
jwt can be verified (using a hashing algorithm) and be decoded (since its only base64 encoded).
if the decoded part is changed, then it will be different from the signage therefore marking it as invalid.
https://discord.com/channels/752553802359505017/1172435746674720798 see here for a visualized diagram on how JWT are produced
@aardani all JWT are signed by default, its how jwt works fundamentally. if you edit the jwt, it becomes invalid. signing is the process of taking a payload and a hashing algorithm to make it so that its impossible to be manipulated
Basset Bleu de GascogneOP
Ohhh gotcha . So if we sign it it’s basically hashing it with the content . And would you suggest me to store the hash in the DB in order to verify if hash ? Or store the actual value of token and hash both to compare ?
JWT means that the state is stored in the client as opposed in the database
therefore, you shouldnt store any user state in the database by default (unless you want to implement extra functionality)
JWT are hashed using a secret key that you use to encode all JWT
Basset Bleu de GascogneOP
Yaa but I have to verify the authorisation of the user.
the hash are already part of the JWT, so just send the JWT to the user's cookie using httpOnly (or just as plain text if you want xD)
but better to store in cookie using httpOnly to better protect against csrf (not completely but it helps)
@aardani the hash are already part of the JWT, so just send the JWT to the user's cookie using httpOnly (or just as plain text if you want xD)
Basset Bleu de GascogneOP
Okay so you have any good resources as in a yt video explaining this I am new to cookies and jwt so was practising creating cookies yesterday . And now I want to try using jwt and see how the flow is
I honestly dont have good resources beside searching up in google and youtube, maybe i need to cite my sources on any article i made like https://discord.com/channels/752553802359505017/1172435746674720798 this one lol
https://jwt.io/introduction obviously, this is a good start
and i use https://github.com/panva/jose to encode and decode the jwts
@aardani but better to store in cookie using httpOnly to better protect against csrf (not completely but it helps)
Basset Bleu de GascogneOP
Yaa checking it out. Not great with visual text haha . Still thanks a lot have saved it . Will work like a charm each time I need to memorise it
So when you sign it it’s hashed and then we need to encode and decode it ?
If it’s hashed there is no way to get the token data back if I am not wrong
yes theres 2 part
theres the base64 encoded part
and the hashed part based on the first part
just see the diagram i made in that link, maybe you can ask question there instead
Basset Bleu de GascogneOP
Sure will do it thanks so cookies was an older way basically ?
And jwt is the more secure and safer way
JWT is the content of the cookie
Cookie is the mean to store stuff in browser
its still used to store JWT :v
Storing Session in database was an older, still currently used, way, to be more precise
JWT is the newer one
its always JWT versus DB Session (and a combination of both to combine both of the benefit)
@aardani its always JWT versus DB Session (and a combination of both to combine both of the benefit)
Basset Bleu de GascogneOP
Oh this makes sense .
Thanks a lot it makes more sense. Now , obviously I will have queries once I start creating it will hit you up.
yeah, feel free to ask me in this discord/create new help-forum
Basset Bleu de GascogneOP
I really want to nail down this part .
Thanks a lot @aardani