How to use with `express-session` | Socket.IO
import
{
Request
,
Response
}
from
"express"
;
import
{
Session
}
from
"express-session"
;
import
{
IncomingMessage
}
from
"http"
;
declare
module
"http"
{
interface
IncomingMessage
{
cookieHolder
?
:
string
,
session
:
Session
&
{
count
:
number
}
}
}
const
io
=
new
Server
(
httpServer
,
{
allowRequest
:
(
req
,
callback
)
=>
{
const
fakeRes
=
{
getHeader
(
)
{
return
[
]
;
}
,
setHeader
(
key
:
string
,
values
:
string
[
]
)
{
req
.
cookieHolder
=
values
[
0
]
;
}
,
writeHead
(
)
{
}
,
}
;
sessionMiddleware
(
req
as
Request
,
fakeRes
as
unknown
as
Response
,
(
)
=>
{
if
(
req
.
session
)
{
fakeRes
.
writeHead
(
)
;
req
.
session
.
save
(
)
;
}
callback
(
null
,
true
)
;
}
)
;
}
,
}
)
;
io
.
engine
.
on
(
"initial_headers"
,
(
headers
:
{
[
key
:
string
]
:
string
}
,
req
:
IncomingMessage
)
=>
{
if
(
req
.
cookieHolder
)
{
headers
[
"set-cookie"
]
=
req
.
cookieHolder
;
delete
req
.
cookieHolder
;
}
}
)
;