Skip to content

Commit b9b0b1e

Browse files
committed
Demonstrate NODE_ENV conditional cookie options
Makes sense to showcase them directly rather than just via text example after the fact
1 parent 973251c commit b9b0b1e

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

nodeJS/authentication/session_based_authentication.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ app.use(session({
8787
saveUninitialized: false,
8888
secret: process.env.SESSION_SECRET,
8989
cookie: {
90-
httpOnly: true,
90+
httpOnly: process.env.NODE_ENV === 'prod',
91+
secure: process.env.NODE_ENV === 'prod',
9192
maxAge: 2 * 24 * 60 * 60 * 1000, // 2 days
9293
},
9394
}));
@@ -117,7 +118,7 @@ We then set a **session secret** which we define in our `.env` file since it's,
117118

118119
#### Cookie options
119120

120-
Lastly, we pass in options for the cookies that will be created by express-session. In our example, we make it inaccessible to JavaScript on the front-end and set a 2-day expiry. You can always use environment variables to set values or even conditionally set them (e.g. `httpOnly: process.env.NODE_ENV === "prod"` can allow you to access session cookies via front-end JavaScript in development but prevent it in production).
121+
Lastly, we pass in options for the cookies that will be created by express-session. In our example, we set a 2-day expiry and conditionally set the `httpOnly` and `secure` properties so that they're only true when in production. This is so that when we're developing locally with localhost, we can still access the cookie via `document.cookie` on the front end if necessary, and still allow the cookie to be set over HTTP (we only want to limit the cookie to HTTPS connections when deployed).
121122

122123
### Creating users
123124

0 commit comments

Comments
 (0)