@@ -11,6 +11,7 @@ export function sessionMiddleware(options: SessionOptions): MiddlewareHandler {
1111 const expireAfterSeconds = options . expireAfterSeconds
1212 const cookieOptions = options . cookieOptions
1313 const sessionCookieName = options . sessionCookieName || 'session'
14+ const autoExtendExpiration = options . autoExtendExpiration ?? false
1415
1516 if ( options . encryptionKey !== undefined ) {
1617 if ( typeof options . encryptionKey === 'function' ) {
@@ -37,7 +38,7 @@ export function sessionMiddleware(options: SessionOptions): MiddlewareHandler {
3738 }
3839
3940 const middleware = createMiddleware ( async ( c , next ) => {
40- const session = new Session
41+ const session = new Session ( expireAfterSeconds )
4142 let sid = ''
4243 let session_data : SessionData | null | undefined
4344 let createNewSession = false
@@ -65,7 +66,9 @@ export function sessionMiddleware(options: SessionOptions): MiddlewareHandler {
6566 session . setCache ( session_data )
6667
6768 if ( session . sessionValid ( ) ) {
68- session . reupSession ( expireAfterSeconds )
69+ if ( autoExtendExpiration ) {
70+ session . reupSession ( )
71+ }
6972 } else {
7073 store instanceof CookieStore ? await store . deleteSession ( c ) : await store . deleteSession ( sid )
7174 createNewSession = true
@@ -93,19 +96,25 @@ export function sessionMiddleware(options: SessionOptions): MiddlewareHandler {
9396 await store . createSession ( sid , defaultData )
9497 }
9598
96- session . setCache ( defaultData )
99+ session . setCache ( defaultData , true )
97100 }
98101
99102 if ( ! ( store instanceof CookieStore ) ) {
100103 setCookie ( c , sessionCookieName , encryptionKey ? await encrypt ( encryptionKey , sid ) : sid , cookieOptions )
101104 }
102105
103- session . updateAccess ( )
106+ if ( autoExtendExpiration ) {
107+ session . updateAccess ( )
108+ }
104109
105110 c . set ( 'session' , session )
106111
107112 await next ( )
108113
114+ if ( session . isStale ( ) ) {
115+ session . touch ( )
116+ }
117+
109118 const shouldDelete = session . getCache ( ) . _delete ;
110119 const shouldRotateSessionKey = c . get ( "session_key_rotation" ) === true ;
111120 const storeIsCookieStore = store instanceof CookieStore ;
@@ -146,7 +155,8 @@ export function sessionMiddleware(options: SessionOptions): MiddlewareHandler {
146155 */
147156 const shouldPersistSession =
148157 ! shouldDelete &&
149- ( ! shouldRotateSessionKey || storeIsCookieStore ) ;
158+ ( ! shouldRotateSessionKey || storeIsCookieStore ) &&
159+ session . isStale ( ) ;
150160
151161 if ( shouldPersistSession ) {
152162 store instanceof CookieStore
0 commit comments