Morpheme AI 2:34 PM
I'd be happy to help you build a REST API with Node.js! Let me walk you through the key steps.

First, set up your project with Express.js — the most popular Node.js web framework:
bash
mkdir my-api && cd my-api
npm init -y
npm install express cors dotenv
You 2:36 PM
Can you show me how to add JWT authentication middleware?
Morpheme AI 2:36 PM
Here's a complete JWT middleware implementation:
javascript
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

// Auth middleware
const authenticate = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json({
      error: 'Access denied. No token provided.'
    });
  }

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token.' });
  }
};

// Public route
app.post('/auth/login', (req, res) => {
  const { email, password } = req.body;
  // Validate credentials…
  const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, {
    expiresIn: '7d'
  });
  res.json({ token });
});

// Protected route
app.get('/api/profile', authenticate, (req, res) => {
  res.json({ user: req.user });
});

app.listen(3000, () => console.log('Server running on :3000'));

Press Enter to send  ·  Shift+Enter for new line