cookie-parser (쿠키에 저장하는 라이브러리)

Category
스터디노트 Express
Status
Published
Tags
Cookie
express
Description
Published
Slug
Express.js 애플리케이션에서 쿠키를 쉽게 파싱하고 설정할 수 있도록 도와주는 미들웨어
 

1. cookie-parser 설치

npm install cookie-parser

2. Express 애플리케이션에 cookie-parser 추가

cookie-parser를 Express 애플리케이션에 추가하여 사용
javascriptconst express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); // 'secret-key'는 서명된 쿠키를 사용하는 경우 필요 app.use(cookieParser('secret-key')); app.get('/', (req, res) => { // 쿠키 읽기 console.log('Cookies: ', req.cookies); // 서명된 쿠키 읽기 console.log('Signed Cookies: ', req.signedCookies); // 쿠키 설정 res.cookie('exampleCookie', 'cookieValue', { maxAge: 900000, httpOnly: true }); res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
 

쿠키 읽기

cookie-parser를 사용하면 클라이언트가 전송한 쿠키를 req.cookies 객체에서 읽을 수 있음
javascriptapp.get('/read-cookie', (req, res) => { console.log('Cookies:', req.cookies); res.send(req.cookies); });

서명된 쿠키 읽기

서명된 쿠키를 사용할 경우 req.signedCookies 객체에서 읽을 수 있음.
서명된 쿠키는 데이터의 무결성을 확인할 수 있음
javascriptapp.get('/read-signed-cookie', (req, res) => { console.log('Signed Cookies:', req.signedCookies); res.send(req.signedCookies); });

쿠키 설정

서버에서 클라이언트로 쿠키를 설정할 때는 res.cookie() 메서드를 사용.
쿠키의 이름, 값 및 옵션을 인수로 받음.
javascriptapp.get('/set-cookie', (req, res) => { res.cookie('exampleCookie', 'cookieValue', { maxAge: 900000, httpOnly: true }); res.send('Cookie has been set'); });

쿠키 삭제

쿠키를 삭제할 때는 res.clearCookie() 메서드를 사용
javascriptapp.get('/clear-cookie', (req, res) => { res.clearCookie('exampleCookie'); res.send('Cookie has been cleared'); });
 
maxAge: 쿠키의 만료 시간을 밀리초 단위로 설정
httpOnlytrue로 설정하면 클라이언트 측 JavaScript에서 쿠키에 접근할 수 없음
securetrue로 설정하면 HTTPS를 통해서만 쿠키가 전송됨
signedtrue로 설정하면 쿠키가 서명됨
javascriptapp.get('/set-secure-cookie', (req, res) => { res.cookie('secureCookie', 'secureValue', { maxAge: 900000, httpOnly: true, secure: true, signed: true }); res.send('Secure cookie has been set'); });