DEV Community

Discussion on: Authentication and Sessions for MVC Apps with NestJS

Collapse
 
ozzythegiant profile image
Oziel Perez • Edited

I would like to post a minor correction/suggestion. If this is written for a REST API, request.logout() will only remove the user from the session, but the session itself won't be removed from the session store. Instead, in the logout route you should write something like this:

@Get("logout") 
public async logout(@Request() request: any, @Response() response: ExpressResponse): Promise<void> {
    request.session.destroy(() => {
        response.cookie(this.config.get("SESSION_NAME"), "", {
            domain: this.config.get("SESSION_DOMAIN"),
            path: "/",
            httpOnly: true,
            maxAge: 0,
            expires: new Date(0)
        })
        response.end()
    })
}
Enter fullscreen mode Exit fullscreen mode

where ExpressResponse is the Response type from express, so as not to clash with Response type from @nestjs/common

request.session.destroy() will remove the session from the store, and on the callback, the session cookie must be deleted since neither Nest nor Passport seem to do this for you. this.config.get("SESSION_NAME") will retrieve the cookie name from a .env file, assuming you set up @nestjs/config library; otherwise just type in the name of the session cookie which by default is connect.sid. Lastly, response.end() will finish the request manually since it the response object was injected.

EDIT: the previous response.clearCookie() call will not work if you had set httpOnly to true, so you must specify the whole cookie's parameters as shown above. Apparently all the previous parameters have to match except max age and expires.