This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Core Tasks

How to accomplish specific tasks with altseven.

Task-oriented pages: communicating with a back end, WebSockets, and authentication.

In This Section:

1 - Remote Modules

Defining API endpoints as remote modules and calling them with fetch/invoke.

Remote modules describe your back-end API in one place; the remote manager turns them into fetch calls with token handling included.

Defining modules

Pass modules in the remote option. Every app needs at least remote: {} — without the option at all, init() throws.

export const myApp = new Application( {
	remote: {
		modules: {
			user: {
				read:     { url: "/api/users/:userID" },
				readAll:  { url: "/api/users" },
				create:   { url: "/api/users" },
				update:   { url: "/api/users/:userID" },
				destroy:  { url: "/api/users/:userID" },
				search:   { url: "/api/users/search", params: { method: "POST" } }
			}
		},
		useTokens: true,                 // default: send the session token with secure calls
		tokenType: "X-Token",            // or "access_token" (Authorization: Bearer)
		credentials: "same-origin"       // "include" for SAML / cross-origin cookie SSO
	}
} );

Method shapes:

  • Object form { url, params } — the framework performs the fetch. Standard action names map to HTTP verbs: create → POST, read/readAll → GET, update → PUT, destroy → DELETE. :param segments in the URL are replaced from the params object. Custom names use params.method (default GET) and params.headers.
  • Function form — receives the params object and returns a fetch Response; use it when you need full control.

Calling methods

// invoke takes "module.action" strings
const response = await myApp.remote.invoke( "user.read", { userID: 7 } );
const user = await response.json();

const created = await myApp.remote.invoke( "user.create", { name: "Rob" } );

// custom methods work the same way
const found = await myApp.remote.invoke( "user.search", { q: "rob" } );

When called through a Service, entity conversion, caching and deduplication happen automatically — prefer services for anything entity-shaped.

Raw fetch

myApp.remote.fetch( uri, params, secure ) is the escape hatch:

const response = await myApp.remote.fetch(
	"/api/widgets/42",
	{ method: "GET" },
	true          // secure = attach the session token
);

With useTokens: true, secure calls send the token — as the X-Token header (default) or as Authorization: Bearer <token> when tokenType is "access_token". The token is set at login from the corresponding response header and kept in sessionStorage, so it survives page reloads.

Authentication endpoints

The loginURL, logoutURL and refreshURL settings define the three built-in auth endpoints; see Authentication.

Set credentials: "include" so every fetch sends cookies cross-origin (and the server must answer the CORS preflight with the right Access-Control-Allow-Credentials). This is how altseven apps integrate with a SAML identity provider: the session lives in cookies, not in the token header.

2 - WebSockets

Raw WebSocket connections and managed sessions with automatic reconnection.

The remote manager provides webSocket() for a raw connection and webSocketSession() (9.1.0) for a managed session with exponential backoff, ping/pong zombie detection, and reconnect on network recovery.

Raw WebSocket

const ws = myApp.remote.webSocket(
	"/ws/notifications",       // ws:// / wss:// URL, or a path (scheme chosen by isSecure)
	function( data ) {
		// data is the parsed JSON message
		console.log( "notification:", data );
	},
	true                        // isSecure → wss://
);

The URL is validated up front: an empty or non-string URL throws a TypeError at the call site instead of producing ws://undefined/.... With useTokens: true, the session token is appended as a ?token= query parameter.

A raw socket is exactly that — if it drops, it stays dropped. For anything that should survive network hiccups, use a session.

Managed sessions

webSocketSession( options ) returns a WebSocketSession:

const session = myApp.remote.webSocketSession( {
	url: "/ws/notifications",
	isSecure: true,                       // default: wss://
	handleMessage: function( data ) {
		// required — called with each parsed message
		notificationBell.setState( { items: data.items } );
	},
	onOpen: function( socket ) {
		// optional — called after each successful open; subscribe here
		socket.send( JSON.stringify( { type: "subscribe", topic: "tasks" } ) );
	},
	ping: {                                // optional — zombie detection
		interval: 30000,                   // ping every 30s
		timeout: 5000,                     // force-close if no pong in 5s
		send: ( socket ) => socket.send( JSON.stringify( { type: "ping" } ) ),
		isPong: ( data ) => data.type === "pong"
	},
	beforeReconnect: async function() {
		// optional — return false to give up permanently (e.g. logged out);
		// throw to treat the failure as transient (backoff continues)
		return myApp.authenticated;
	},
	backoff: { initial: 1000, max: 30000, jitter: true },
	maxAttempts: Infinity
} );

What the session does for you:

  • Exponential backoff with jitter between reconnect attempts (default 1s → 30s cap), so a flapping server isn’t met by a thundering herd.
  • Ping/pong zombie detection — a half-open TCP connection that silently stopped delivering messages is force-closed so the reconnect logic can take over.
  • Network awareness — online and visibilitychange events trigger an immediate reconnect attempt instead of waiting out the backoff timer.
  • State machine — session.state is one of idle, connecting, open, reconnecting, closed.

Sending and closing

session.send( JSON.stringify( { type: "chat", text: "hello" } ) );
// → true if sent, false if the socket is not currently open

session.close();   // explicit shutdown — no more reconnects after this

Pattern: socket events into the event system

A common integration maps socket messages to pub/sub topics, so views can subscribe like they do to everything else:

const session = myApp.remote.webSocketSession( {
	url: "/ws/events",
	handleMessage: ( data ) => {
		// data: { topic: "task.updated", payload: {...} }
		myApp.events.publish( data.topic, data.payload );
	},
	onOpen: ( socket ) => socket.send( JSON.stringify( { type: "subscribe-all" } ) )
} );

3 - Authentication

How the built-in authentication system works: tokens, refresh, sessions.

altseven ships an authentication mechanism built on HTTP Basic auth for login and a session token for subsequent requests, with an automatic refresh cycle.

See the authentication tutorial for a step-by-step login form example; this page describes the machinery.

Configuration

export const myApp = new Application( {
	remote: {
		loginURL: "/api/auth/login",
		logoutURL: "/api/auth/logout",
		refreshURL: "/api/auth/refresh",
		useTokens: true,           // default
		tokenType: "X-Token"       // or "access_token"
	},
	security: {
		enabled: true,             // default
		userArgs: { userID: "" }   // default fields for the session user
	},
	auth: {
		sessionTimeout: 15 * 60 * 1000   // default: 15 minutes
	}
} );

With security enabled, Application.init() awaits an authentication check before your startup code proceeds: it calls the auth.refresh remote method and resolves myApp.authenticated and myApp.user.

The three endpoints

login — POST loginURL. The framework sends HTTP Basic auth (Authorization: Basic base64(username:password)) and a JSON body { rememberMe: boolean }. Your server responds with:

  • the session token in the X-Token response header (or Access_token if tokenType: "access_token"), which the framework stores in sessionStorage
  • a JSON body { success: true, user: { ... } } (or { success: false, ... })

refresh — GET refreshURL with the token attached. Your server responds { authenticated: boolean, user: { ... } }. A 401 is treated as { authenticated: false }. This endpoint is called:

  • once at application startup (the isAuthenticated check)
  • periodically, on the auth.sessionTimeout timer, to keep the session alive

logout — POST logoutURL. On { success: true } the framework invalidates the session (clears the token, resets the user).

The flow from your code

You never call these endpoints directly — publish the built-in events:

myApp.events.publish( "auth.login", {
	username, password, rememberMe,
	success: function( json ) { /* navigate into the app */ },
	failure: function( json ) { /* show the error */ }
} );

myApp.events.publish( "auth.logout", { success: ( json ) => ... } );

success/failure may be functions, event topic names, or router paths (when the router is configured). See the tutorial for the full pattern.

Session state

  • The current user is held in myApp.user, mirrored into sessionStorage and (when a model is in use) myApp.model.get( "user" ).
  • myApp.security.isAuthenticated() returns a promise of { authenticated: boolean, user }; concurrent calls share one refresh request.
  • myApp.security.invalidateSession() clears the token and resets the user — the auth.sessionTimeout and auth.invalidateSession topics do this too.
  • When a refresh call fails unexpectedly, the framework publishes auth.logout itself.

SAML / SSO variants

Set remote.credentials: "include" to rely on cookie sessions instead of tokens (the login/refresh/logout calls then send cookies cross-origin). The rest of the flow — the three endpoints and the events — is unchanged.