{"id":13990,"library":"secure-web-token","title":"Secure Web Token (SWT)","description":"Secure Web Token (SWT) is a Node.js library offering a security-focused alternative to traditional JSON Web Tokens (JWTs). Unlike JWTs, which are merely Base64 encoded, SWT employs AES-256-GCM encryption for payloads and implements server-side session binding, making tokens device-bound and preventing reuse on other devices. This approach significantly enhances security by making stolen tokens useless for attackers. The current stable version is 1.2.8. It provides a simple API with `sign()` and `verify()` functions, supporting expiry and HttpOnly session cookies. Key differentiators include full payload encryption, true device binding, and server-side session management, making it suitable for high-security applications like admin panels, SaaS dashboards, and internal tools where preventing token leakage and session hijacking is critical.","status":"active","version":"1.2.8","language":"javascript","source_language":"en","source_url":"https://github.com/MintuSingh07/node-securewebtoken","tags":["javascript","token","security","typescript"],"install":[{"cmd":"npm install secure-web-token","lang":"bash","label":"npm"},{"cmd":"yarn add secure-web-token","lang":"bash","label":"yarn"},{"cmd":"pnpm add secure-web-token","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primarily used in ESM contexts for creating encrypted, device-bound tokens. While CommonJS `require` syntax is supported, ESM is idiomatic for TypeScript projects.","wrong":"const sign = require('secure-web-token').sign","symbol":"sign","correct":"import { sign } from 'secure-web-token'"},{"note":"A named export; ensure you use destructuring for import. This function validates and decrypts tokens, requiring session context like `sessionId` and `fingerprint`.","wrong":"import verify from 'secure-web-token'","symbol":"verify","correct":"import { verify } from 'secure-web-token'"},{"note":"Used to retrieve the configured session store instance. By default, it returns an in-memory store, which should be replaced with a persistent solution for production.","wrong":"const { getStore } = require('secure-web-token')","symbol":"getStore","correct":"import { getStore } from 'secure-web-token'"}],"quickstart":{"code":"import express from \"express\";\nimport cookieParser from \"cookie-parser\";\nimport { sign, verify, getStore } from \"secure-web-token\";\n\nconst app = express();\napp.use(express.json());\napp.use(cookieParser());\n\nconst SECRET = process.env.SWT_SECRET ?? 'a-very-secure-random-secret-key-of-at-least-32-characters'; // Use environment variable for production\nconst store = getStore(\"memory\"); // Default in-memory store, replace with persistent for production\n\n// Define a simple user for demonstration\nconst demoUser = { userId: 123, username: \"testuser\" };\n\n// --- Sign Token Example ---\napp.post('/login', (req, res) => {\n  // In a real app, validate user credentials here\n  const { token, sessionId } = sign(demoUser, SECRET, {\n    fingerprint: true, // Enable device binding\n    store: \"memory\", // Use the configured store\n    expiresIn: 3600 // Token expires in 1 hour\n  });\n\n  // Set HttpOnly cookie for sessionId\n  res.cookie(\"swt_session\", sessionId, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax' });\n  res.json({ message: \"Login successful\", token });\n});\n\n// --- Verify Token Example ---\napp.get('/protected', (req, res) => {\n  try {\n    const sessionId = req.cookies.swt_session;\n    const token = req.headers.authorization?.split(\" \")[1];\n\n    if (!sessionId || !token) {\n      return res.status(401).json({ error: \"Authentication required\" });\n    }\n\n    // Retrieve session data (e.g., fingerprint) from the store\n    const session = store.getSession(sessionId);\n    if (!session) {\n        return res.status(401).json({ error: \"Session not found or expired\" });\n    }\n\n    const payload = verify(token, SECRET, {\n      sessionId,\n      fingerprint: session.fingerprint, // Crucial for device binding\n      store: \"memory\" // Use the configured store\n    });\n\n    res.json({ message: \"Access granted!\", user: payload.data });\n  } catch (error) {\n    console.error(\"Verification failed:\", error);\n    res.status(401).json({ error: \"Unauthorized access\" });\n  }\n});\n\nconst PORT = 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log(\"Try: POST /login and then GET /protected with the token and cookie.\");\n});","lang":"typescript","description":"Demonstrates a basic Express.js server using `secure-web-token` to handle user login and protect a route. It shows how to `sign` a token with device binding, set an HttpOnly session cookie, and then `verify` the token and session context for authorized access."},"warnings":[{"fix":"Implement and configure a persistent session store (e.g., Redis, database) by providing a custom `store` object to the `sign` and `verify` functions, or by extending `getStore`.","message":"The default session store is in-memory. This store is volatile, meaning all sessions are lost on application restart and it does not support multi-instance deployments (load balancing). This is unsuitable for production environments requiring persistence or scalability.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Generate a strong, long, random secret. Store it securely (e.g., environment variable, KMS) and ensure all instances of your application use the exact same secret.","message":"The `SECRET` key is critical for token encryption and decryption. Using a weak secret, exposing it publicly, or failing to keep it consistent across all application instances will lead to token validation failures or severe security vulnerabilities.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `sessionId` is consistently passed from the client (e.g., HttpOnly cookie) and use it to retrieve the `fingerprint` from your server-side session store, then pass both to `verify` options.","message":"Unlike JWTs, `secure-web-token` is stateful and requires both the `sessionId` (typically from an HttpOnly cookie) and the `fingerprint` (retrieved from your session store) to be explicitly passed to the `verify` function. Failure to provide correct and matching session context will result in authentication failure, as the token is device-bound.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Configure your frontend HTTP client (e.g., Axios, Fetch API) to send credentials (`credentials: 'include'`) and allow the browser to manage the HttpOnly cookie automatically. Do not attempt to access the `swt_session` cookie from JavaScript.","message":"When integrating `secure-web-token` with a frontend framework, ensure HttpOnly cookies are correctly handled for the `sessionId`. Client-side JavaScript should not attempt to read or write the `swt_session` cookie directly, as it's designed for server-only access.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'-256':35 '1.2.8':75 'admin':116 'ae':34 'altern':18 'api':80 'applic':114 'approach':59 'attack':69 'base64':30 'bind':46,100 'bound':51 'cooki':91 'critic':131 'current':71 'dashboard':119 'devic':50,57,99 'device-bound':49 'differenti':93 'employ':33 'encod':31 'encrypt':37,97 'enhanc':61 'expiri':87 'focus':17 'full':95 'function':85 'gcm':36 'high':112 'high-secur':111 'hijack':129 'httpon':89 'implement':41 'includ':94 'intern':121 'javascript':132 'json':21 'jwts':24,26 'key':92 'leakag':126 'librari':12 'like':115 'make':47,64,107 'manag':106 'mere':29 'node.js':11 'offer':13 'panel':117 'payload':39,96 'prevent':53,124 'provid':77 'reus':54 'saa':118 'secur':1,5,16,62,113,134 'security-focus':15 'server':43,103 'server-sid':42,102 'session':45,90,105,128 'side':44,104 'sign':82 'signific':60 'simpl':79 'stabl':72 'stolen':65 'suitabl':109 'support':86 'swt':4,8,32 'token':3,7,23,48,66,125,133 'tool':122 'tradit':20 'true':98 'typescript':135 'unlik':25 'useless':67 'verifi':84 'version':73 'web':2,6,22","created_at":"2026-04-20T01:57:21.607311+00:00","updated_at":"2026-04-20T01:57:21.607311+00:00","problems":[{"fix":"Check if the token is present, unexpired, and correctly signed. Verify that the `sessionId` and associated `fingerprint` provided to `verify` match the server-side session, and that the `SECRET` is identical to the one used during `sign`.","cause":"Token validation failed due to an invalid token, missing session context (`sessionId`, `fingerprint`), or an incorrect secret.","error":"Unauthorized access"},{"fix":"Ensure the `sessionId` is valid and the session exists in the configured store. This often indicates a missing or expired session, or a misconfigured session store (e.g., in-memory store reset).","cause":"The server-side session associated with the `sessionId` could not be found in the store or has expired.","error":"Session not found or expired"},{"fix":"Confirm the `SECRET` key used in `verify` is identical to the one used in `sign`. If the secret is correct, the token may have been tampered with or is corrupted. Ensure the token is passed correctly without modification.","cause":"The token was tampered with, the `SECRET` used for verification is different from the one used for signing, or the token is malformed.","error":"Error: Invalid token signature"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":"https://securewebtoken.vercel.app","github":"https://github.com/MintuSingh07/node-securewebtoken","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/secure-web-token","openapi_spec":null,"status_page":null,"smithery":null,"categories":["auth-security","web-framework","http-networking"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}