Skip to content

Session Management

Managing Session States for the UI

The <np-if> component can be used to conditionally render UI elements based on the user’s authentication state. This component provides three slots:

  • authenticated: Rendered when a session is active.
  • unauthenticated: Rendered when the user is not logged in.
  • unknown: Rendered when the session state is currently unknown.

You can also use the <np-if> component to show different parts of your application based on the user’s authentication state.

<np-if>
<!-- Displayed if a session is active -->
<div slot="authenticated">
<h1>Welcome back!</h1>
<p>You have access to all features.</p>
</div>
<!-- Displayed if the user is not logged in -->
<div slot="unauthenticated">
<h1>Welcome!</h1>
<p>Please log in to access more features.</p>
<np-login></np-login>
</div>
<!-- Displayed when the session state is currently unknown -->
<div slot="unknown">
<h1>Loading...</h1>
<p>Checking your session status.</p>
</div>
</np-if>

This approach ensures that your application provides a seamless user experience by dynamically adjusting the UI based on the user’s session state.

Customizing the Session Duration

Depending on your application’s business domain, the required session duration may vary. This decision typically depends on user activity and the time elapsed since the user first signed in.

Choosing the ideal session lifetime is a balance between security and user experience. Longer sessions enhance UX but may compromise security, and vice versa.

With Nopwd, you have full control over your users’ session lifetimes. You can configure two settings:

  • lifetime: Sets the maximum session duration (up to a year).
  • idletimeout: Optionally sets the inactivity timeout.
<!-- Default: session lifetime is 24 hours with no inactivity threshold -->
<np-login></np-login>
<!-- Set a one-week session lifetime -->
<np-login lifetime="604800"></np-login>
<!-- Set a one-week session lifetime with a one-day inactivity timeout -->
<np-login lifetime="604800" idletimeout="86400"></np-login>

Getting a Fresh Session Token

A session starts when a user authenticates using the <np-login> component.

To retrieve the user’s session token, call the get method:

import { get } from "@nopwdio/sdk-js/dist/core/session";
const session = await get();
if (session === null) {
// User is not authenticated
return;
}
// Accessing the session token
const { token } = session;

Transmitting the Session Token

Your frontend is responsible for sending the token to your server. Typically, this is done by transmitting the token in an Authorization header:

// From your website
const response = await fetch("[your API endpoint]", {
// ...
headers: {
Authorization: `Bearer ${token}`,
},
// ...
});

Verifying the Session Token

Once transmitted to your server, you must verify that the token is valid (generated for your application and not expired). You can do this by:

  • Using our API endpoint (simplest way).
  • Using third-party JWT libraries (recommended).
  • Verifying it yourself.

Using Our API Endpoint

If you don’t have a backend server, for example, if you’re using Webflow, we provide an API endpoint to validate the access token from nopwd.io.

const accessToken = "...";
const myDomain = "mywebsite.com";
const response = await fetch(`https://api.nopwd.io/v0/tokens/${accessToken}`);
if (!response.ok) {
return; // Invalid/expired token
}
// The access token's decoded payload
const jwt = await response.json();
if (jwt.aud !== myDomain) {
return; // Audience mismatch with your website
}

See the API specs here to learn more.

Using Third-Party JWT Libraries

To avoid mistakes in this critical flow, you can use third-party libraries to verify JWT tokens. Check the list of third-party libraries here. Ensure you check for the ES256 algorithm that NoPwd uses.

Here is an example using the battle-tested jose library.

const token = "..."; // The user's access token
const JWKS = createRemoteJWKSet(new URL("https://api.nopwd.io/v0/jwks"));
const { payload } = await jwtVerify(token, JWKS, {
issuer: "nopwd.io",
audience: "[your website domain]", // Your own domain
});

Verifying It Yourself

The token is a JWT token signed using the ES256 asymmetric signing algorithm. Unlike symmetric JWT tokens, which are signed and verified using the same secret key, this asymmetric JWT token is signed using a secret key known only to Nopwd but can be verified using a public key available here.

Checklist:

  • Check that the JWT is well-formed.
  • Ensure the token is issued by nopwd: iss = nopwd.io.
  • Ensure the audience matches your domain: aud = yourwebsite.com.
  • Ensure the token is not expired: now < exp.
  • Verify the signature.

Terminating a Session

A session typically ends when the user logs out using the <np-logout> button component or after a period of inactivity. In such cases, this component emits an np:logout event.

<np-logout></np-logout>
<script type="module">
// Listen to the 'np:logout' event
const el = document.querySelector("np-logout");
el.addEventListener("np:logout", (e) => {
// Session is terminated
});
</script>

You can also terminate a session programmatically using the revoke method:

import { revoke } from "@nopwdio/sdk-js/dist/core/session";
await revoke();

A Word About Security

To enhance security, we use asymmetric cryptography (public-key cryptography) to maintain and verify session validity. The private key is generated and stored only on the end-user device and cannot be extracted even by your web application. Compromising a session token does not compromise the entire session.