Authentication
Overview
Section titled “Overview”NexaSpace provides enterprise-grade authentication out of the box, supporting multiple strategies including OAuth, JWT, and session-based auth.
JWT Authentication
Section titled “JWT Authentication”The most common authentication method for modern applications:
import { NexaSpace, JWTAuth } from 'nexaspace';
const app = new NexaSpace();
// Configure JWT authenticationapp.use(JWTAuth({ secret: process.env.JWT_SECRET, expiresIn: '7d', algorithms: ['HS256']}));
// Protected routeapp.get('/profile', JWTAuth.require(), (req, res) => { res.json({ user: req.user }); });OAuth Integration
Section titled “OAuth Integration”Support for popular OAuth providers:
import { OAuth } from 'nexaspace';
// GitHub OAuthapp.use(OAuth.github({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: '/auth/github/callback'}));
// Google OAuthapp.use(OAuth.google({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: '/auth/google/callback'}));User Registration
Section titled “User Registration”Create a secure user registration endpoint:
import { hash } from 'nexaspace/crypto';
app.post('/register', async (req, res) => { const { email, password } = req.body;
// Validate input if (!email || !password) { return res.status(400).json({ error: 'Missing credentials' }); }
// Hash password const hashedPassword = await hash(password);
// Create user in database const user = await db.users.create({ email, password: hashedPassword });
// Generate token const token = JWTAuth.sign({ userId: user.id });
res.json({ token, user });});Middleware Protection
Section titled “Middleware Protection”Protect entire route groups:
// Public routesapp.get('/public', (req, res) => { res.json({ message: 'Public endpoint' });});
// Protected routes groupapp.group('/api', JWTAuth.require(), (group) => { group.get('/profile', getProfile); group.put('/profile', updateProfile); group.delete('/account', deleteAccount);});