Sessions

Sessions

HTGM is able to create persistent sessions for visitors, allowing data to be persisted across multiple requests. It works by setting a session ID in a cookie, which on subsequent requests will retrieve the session, similar to how sessions work in PHP.

Creating a session

When ready to, a session can be created using context.response.start_session(). This will create a new session, and send the session ID to the client as a cookie.

global.server.add_path("demos/sessions/login", function(_context) {
	_context.response.send_html(@'
		<form action="/demos/sessions/start" method="post">
			<label for="name">Name: </label>
			<input type="text" id="name" name="name">
			<br>
			<input type="submit" value="Submit">
		</form>
	');
});

global.server.add_path("demos/sessions/start", function(_context) {
	var _name = _context.request.get_form("name");
	_context.start_session();
	_context.session.set("name", _name);
	_context.response.send_string($"hello {_name} you have logged in");
});

In the above example, a form is used to submit the username to the login endpoint, which then creates a session and assigns the name to session storage. You can see the demo here.

Reading from a session

If a session cookie is presented, a context.session variable is available of the type Struct.HttpServerLoginSession, which has functions for setting and getting variables. context.has_session() can be used to check whether a session is present and valid.

global.server.add_path("demos/sessions/continue", function(_context) {
	if (_context.has_session()) {
		var _name = _context.session.get("name");
		_context.response.send_string($"hello {_name} you are logged in");
	}
	else {
		_context.response.send_string($"you are not logged in");
	}
});

In the above example, assuming the user has logged in previously, it will be able to fetch the stored username from session storage. You can see the demo here.

Closing a session

Sessions normally have a set validity period. But sessions can be closed early using context.close_session()

global.server.add_path("demos/sessions/logout", function(_context) {
	_context.close_session();
	_context.response.send_string($"You have been logged out");
});

In the above example, the user's session will be closed. You can see the demo here. Once you go here, try going back to the demo link in the previous section, to see that you have logged out.