Skip to content

Commit 96ba90d

Browse files
committed
New: copy of the sessions.md file for reference
1 parent 0946bf8 commit 96ba90d

File tree

1 file changed

+148
-0
lines changed

1 file changed

+148
-0
lines changed

docs/advanced/sessions.es.md

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# Sessions
2+
3+
Sessions allow you to persist a user's data between multiple requests. Sessions work by creating and returning a unique cookie alongside the HTTP response when a new session is initialized. Browsers will automatically detect this cookie and include it in future requests. This allows Vapor to automatically restore a specific user's session in your request handler.
4+
5+
Sessions are great for front-end web applications built in Vapor that serve HTML directly to web browsers. For APIs, we recommend using stateless, [token-based authentication](../security/authentication.md) to persist user data between requests.
6+
7+
## Configuration
8+
9+
10+
To use sessions in a route, the request must pass through `SessionsMiddleware`. The easiest way to achieve this is by adding this middleware globally. It is recommended that you do add this after you declare the cookie factory. This is because Sessions is a struct, therefore it is a value type, and not a reference type. Since it is a value type, you must set the value before using `SessionsMiddleware`.
11+
12+
```swift
13+
app.middleware.use(app.sessions.middleware)
14+
```
15+
16+
If only a subset of your routes utilize sessions, you can instead add `SessionsMiddleware` to a route group.
17+
18+
```swift
19+
let sessions = app.grouped(app.sessions.middleware)
20+
```
21+
22+
The HTTP cookie generated by sessions can be configured using `app.sessions.configuration`. You can change the cookie name and declare a custom function for generating cookie values.
23+
24+
```swift
25+
// Change the cookie name to "foo".
26+
app.sessions.configuration.cookieName = "foo"
27+
28+
// Configures cookie value creation.
29+
app.sessions.configuration.cookieFactory = { sessionID in
30+
.init(string: sessionID.string, isSecure: true)
31+
}
32+
33+
app.middleware.use(app.sessions.middleware)
34+
```
35+
36+
By default, Vapor will use `vapor_session` as the cookie name.
37+
38+
## Drivers
39+
40+
Session drivers are responsible for storing and retrieving session data by identifier. You can create custom drivers by conforming to the `SessionDriver` protocol.
41+
42+
!!! warning
43+
The session driver should be configured _before_ adding `app.sessions.middleware` to your application.
44+
45+
### In-Memory
46+
47+
Vapor utilizes in-memory sessions by default. In-memory sessions require zero configuration and do not persist between application launches which makes them great for testing. To enable in-memory sessions manually, use `.memory`:
48+
49+
```swift
50+
app.sessions.use(.memory)
51+
```
52+
53+
For production use cases, take a look at the other session drivers which utilize databases to persist and share sessions across multiple instances of your app.
54+
55+
### Fluent
56+
57+
Fluent includes support for storing session data in your application's database. This section assumes you have [configured Fluent](../fluent/overview.md) and can connect to a database. The first step is to enable the Fluent sessions driver.
58+
59+
```swift
60+
import Fluent
61+
62+
app.sessions.use(.fluent)
63+
```
64+
65+
This will configure sessions to use the application's default database. To specify a specific database, pass the database's identifier.
66+
67+
```swift
68+
app.sessions.use(.fluent(.sqlite))
69+
```
70+
71+
Finally, add `SessionRecord`'s migration to your database's migrations. This will prepare your database for storing session data in the `_fluent_sessions` schema.
72+
73+
```swift
74+
app.migrations.add(SessionRecord.migration)
75+
```
76+
77+
Make sure to run your application's migrations after adding the new migration. Sessions will now be stored in your application's database allowing them to persist between restarts and be shared between multiple instances of your app.
78+
79+
### Redis
80+
81+
Redis provides support for storing session data in your configured Redis instance. This section assumes you have [configured Redis](../redis/overview.md) and can send commands to the Redis instance.
82+
83+
To use Redis for Sessions, select it when configuring your application:
84+
85+
```swift
86+
import Redis
87+
88+
app.sessions.use(.redis)
89+
```
90+
91+
This will configure sessions to use the Redis sessions driver with the default behavior.
92+
93+
!!! seealso
94+
Refer to [Redis → Sessions](../redis/sessions.md) for more detailed information about Redis and Sessions.
95+
96+
## Session Data
97+
98+
Now that sessions are configured, you are ready to persist data between requests. New sessions are initialized automatically when data is added to `req.session`. The example route handler below accepts a dynamic route parameter and adds the value to `req.session.data`.
99+
100+
```swift
101+
app.get("set", ":value") { req -> HTTPStatus in
102+
req.session.data["name"] = req.parameters.get("value")
103+
return .ok
104+
}
105+
```
106+
107+
Use the following request to initialize a session with the name Vapor.
108+
109+
```http
110+
GET /set/vapor HTTP/1.1
111+
content-length: 0
112+
```
113+
114+
You should receive a response similar to the following:
115+
116+
```http
117+
HTTP/1.1 200 OK
118+
content-length: 0
119+
set-cookie: vapor-session=123; Expires=Fri, 10 Apr 2020 21:08:09 GMT; Path=/
120+
```
121+
122+
Notice the `set-cookie` header has been added automatically to the response after adding data to `req.session`. Including this cookie in subsequent requests will allow access to the session data.
123+
124+
Add the following route handler for accessing the name value from the session.
125+
126+
```swift
127+
app.get("get") { req -> String in
128+
req.session.data["name"] ?? "n/a"
129+
}
130+
```
131+
132+
Use the following request to access this route while making sure to pass the cookie value from the previous response.
133+
134+
```http
135+
GET /get HTTP/1.1
136+
cookie: vapor-session=123
137+
```
138+
139+
You should see the name Vapor returned in the response. You can add or remove data from the session as you see fit. Session data will be synchronized with the session driver automatically before returning the HTTP response.
140+
141+
To end a session, use `req.session.destroy`. This will delete the data from the session driver and invalidate the session cookie.
142+
143+
```swift
144+
app.get("del") { req -> HTTPStatus in
145+
req.session.destroy()
146+
return .ok
147+
}
148+
```

0 commit comments

Comments
 (0)