Skip to content

Authentication

NexaSpace provides enterprise-grade authentication out of the box, supporting multiple strategies including OAuth, JWT, and session-based auth.

The most common authentication method for modern applications:

import { NexaSpace, JWTAuth } from 'nexaspace';
const app = new NexaSpace();
// Configure JWT authentication
app.use(JWTAuth({
secret: process.env.JWT_SECRET,
expiresIn: '7d',
algorithms: ['HS256']
}));
// Protected route
app.get('/profile',
JWTAuth.require(),
(req, res) => {
res.json({ user: req.user });
}
);

Support for popular OAuth providers:

import { OAuth } from 'nexaspace';
// GitHub OAuth
app.use(OAuth.github({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: '/auth/github/callback'
}));
// Google OAuth
app.use(OAuth.google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
}));

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 });
});

Protect entire route groups:

// Public routes
app.get('/public', (req, res) => {
res.json({ message: 'Public endpoint' });
});
// Protected routes group
app.group('/api', JWTAuth.require(), (group) => {
group.get('/profile', getProfile);
group.put('/profile', updateProfile);
group.delete('/account', deleteAccount);
});