๐ ๋ฌธ์ ์ํฉ
require๋ฌธ์ import๋ก ๋ฐ๊พธ๋ ์์ ์ ํ๋ ๋์ค const express = require(’express’)๋ฅผ import express from ‘express’๋ก ๋ฐ๊ฟจ๋๋ ์๋ ๋ถ๋ถ์์ Property 'session' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339) ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
๐ก ํด๊ฒฐ ๋ฐฉ์
์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์๋ ๋จผ์ @types/express-session์ ์ค์นํด์ค์ผ ํ๋ค. ์๋ ๋ช ๋ น์ด๋ฅผ ์คํํ๋๋ก ํ์.
npm install -D @types/express-session@1.17.0
์ดํ ๊ทธ๋ฌ๊ณ ๋๋ฉด req.logout๊ณผ req.session.destroy๊ฐ ๊ฐ๊ฐ ์ฝ๋ฐฑํจ์๋ฅผ ์๊ตฌํ๊ธฐ ๋๋ฌธ์ req.logout์ด ๋๋ฉด req.session.destroy๋ฅผ ํ๋๋ก ํจ์๋ฅผ ์ง์ฃผ์๋ค. ์ดํ ์ฑ๊ณตํ๋ค๋ ๊ฐ์ ๋ฆฌํดํด์ฃผ๋ success ํจ์(์ปค์คํ ํจ์)๋ฅผ ํธ์ถํด์ฃผ์๋ค.
import { Request, Response } from 'express';
import { responseMessage, statusCode } from '../modules/constants';
import { success } from '../modules/util';
const logout = async (req: Request, res: Response) => {
req.logout(() => {
req.session.destroy(() => {
success(res, statusCode.OK, responseMessage.SUCCESS, {
session: req.session,
});
});
});
};
export { logout };
์์ ๊ฐ์ด ํ๋ฉด ์๋ฌ๋ ํด๊ฒฐ๋๋ค.
โญ๏ธ req.logout vs req.session.destroy
req.logout๊ณผ req.session.destroy์ ์ฐจ์ด๊ฐ ๊ถ๊ธํด์ ธ์ ์๋์ ๊ฐ์ด ์ฝ์์ ๊ฐ์ ์ฐ์ด๋ดค๋ค.
import { Request, Response } from 'express';
import { responseMessage, statusCode } from '../modules/constants';
import { success } from '../modules/util';
const logout = async (req: Request, res: Response) => {
console.log(`session before logout ${JSON.stringify(req.session, null, 4)}`);
req.logout(() => {
console.log(`session after logout ${JSON.stringify(req.session, null, 4)}`);
req.session.destroy(() => {
console.log(
`session after destroy ${JSON.stringify(req.session, null, 4)}`,
);
success(res, statusCode.OK, responseMessage.SUCCESS, {
session: req.session,
});
});
});
};
export { logout };
๊ทธ ๊ฒฐ๊ณผ๋ ์๋์ ๊ฐ๋ค.
๊ทธ๋ฐ๋ฐ ์ฌ์ค ๋ก๊ทธ์์์ ์ํ๊ณ ๋ฐ๋ก req.session.destroy๋ฅผ ํด๋ session์ undefined๊ฐ ์ฐํ๋ค. logout์ ์๋ตํ ์ฝ๋์ ๊ทธ ์คํ ๊ฒฐ๊ณผ๋ ๊ฐ๊ฐ ๋ค์๊ณผ ๊ฐ๋ค.
import { Request, Response } from 'express';
import { responseMessage, statusCode } from '../modules/constants';
import { success } from '../modules/util';
const logout = async (req: Request, res: Response) => {
console.log(`session before logout ${JSON.stringify(req.session, null, 4)}`);
req.session.destroy(() => {
console.log(
`session after destroy ${JSON.stringify(req.session, null, 4)}`,
);
success(res, statusCode.OK, responseMessage.SUCCESS, {
session: req.session,
});
});
};
export { logout };
๊ทธ๋์ ์ฑGPT์๊ฒ ๋ฌผ์ด๋ณธ ๊ฒฐ๊ณผ ๊ฒฐ๋ก ์ ์๋์ ๊ฐ๋ค.
session.logout์ ๋จ์ํ Passport์ ์ํด ์ถ๊ฐ๋ req.user property๋ฅผ ์ง์ฐ๋ ๊ฒ์ด๋ค. ๊ทธ๋ฌ๋ servier-side session์ ์ ์ ์ ๊ด๋ จ๋ ์ ๋ณด๊ฐ ๋จ์์์ ๊ฒ์ ๋๋นํ์ฌ session.destroy๊น์ง ํด์ฃผ๋ ๊ฒ์ด๋ผ๊ณ ํ๋ค. ๊ทธ๋ ์ง ์์ผ๋ฉด ์ฐ์ด์ด ์ค๋ ๋ค๋ฅธ ์์ฒญ(Request)์ด ์ ์ ๊ฐ ๋ก๊ทธ์์์ ํ ์ํ์์๋ ๋ถ๊ตฌํ๊ณ ์ ์ ๊ด๋ จ ์ ๋ณด์ ์ ๊ทผํ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
๋๊ธ