Claude
Skills
Sign in
Back

mern-patterns

Included with Lifetime
$97 forever

MERN stack patterns including React with Vite, Express middleware, MongoDB schemas, API Gateway architecture, session management, error handling, and testing strategies. Activate for MERN development, microservices architecture, and full-stack JavaScript applications.

Web Dev

What this skill does


# MERN Stack Patterns Skill

Comprehensive MERN stack development patterns for the keycloak-alpha multi-tenant platform with 8 microservices.

## When to Use This Skill

Activate this skill when:
- Building React + Vite frontend applications
- Implementing Express microservices
- Designing MongoDB schemas and data models
- Setting up API Gateway architecture
- Implementing session and cookie management
- Adding error handling and validation
- Writing tests for MERN stack applications

## keycloak-alpha Project Structure

```
keycloak-alpha/
├── apps/
│   ├── web-app/                    # Main React + Vite SPA
│   │   ├── src/
│   │   │   ├── components/
│   │   │   ├── pages/
│   │   │   ├── hooks/
│   │   │   ├── contexts/
│   │   │   ├── config/
│   │   │   ├── utils/
│   │   │   └── main.jsx
│   │   ├── vite.config.js
│   │   └── package.json
│   └── admin-portal/               # Admin dashboard (React + Vite)
│
├── services/
│   ├── api-gateway/                # Express API Gateway
│   ├── user-service/               # User management
│   ├── org-service/                # Organization management
│   ├── tenant-service/             # Multi-tenant provisioning
│   ├── notification-service/       # Email/SMS notifications
│   ├── billing-service/            # Stripe integration
│   ├── analytics-service/          # Usage analytics
│   └── keycloak-service/          # Keycloak integration
│
├── routes/
│   ├── api/
│   │   ├── users.js
│   │   ├── organizations.js
│   │   └── tenants.js
│   └── index.js
│
├── shared/
│   ├── types/
│   ├── utils/
│   └── constants/
│
└── package.json
```

## React + Vite Frontend Patterns

### Vite Configuration

```javascript
// apps/web-app/vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],

  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@components': path.resolve(__dirname, './src/components'),
      '@hooks': path.resolve(__dirname, './src/hooks'),
      '@contexts': path.resolve(__dirname, './src/contexts'),
      '@utils': path.resolve(__dirname, './src/utils'),
      '@config': path.resolve(__dirname, './src/config'),
    }
  },

  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        changeOrigin: true,
      }
    }
  },

  build: {
    outDir: 'dist',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          'vendor': ['react', 'react-dom', 'react-router-dom'],
          'keycloak': ['keycloak-js'],
          'ui': ['@chakra-ui/react', '@emotion/react']
        }
      }
    }
  },

  optimizeDeps: {
    include: ['react', 'react-dom', 'keycloak-js']
  }
});
```

### Component Organization

```javascript
// apps/web-app/src/components/features/UserProfile/index.jsx
import { useState, useEffect } from 'react';
import { useAuth } from '@hooks/useAuth';
import { useToast } from '@chakra-ui/react';
import { updateUserProfile } from '@/api/users';

export function UserProfile() {
  const { user } = useAuth();
  const toast = useToast();
  const [profile, setProfile] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchProfile();
  }, []);

  async function fetchProfile() {
    setLoading(true);
    try {
      const data = await getUserProfile(user.sub);
      setProfile(data);
    } catch (error) {
      toast({
        title: 'Error loading profile',
        description: error.message,
        status: 'error',
        duration: 5000,
      });
    } finally {
      setLoading(false);
    }
  }

  async function handleSubmit(formData) {
    try {
      await updateUserProfile(user.sub, formData);
      toast({
        title: 'Profile updated',
        status: 'success',
        duration: 3000,
      });
    } catch (error) {
      toast({
        title: 'Update failed',
        description: error.message,
        status: 'error',
        duration: 5000,
      });
    }
  }

  if (loading) return <Spinner />;
  if (!profile) return <Alert>Profile not found</Alert>;

  return <ProfileForm profile={profile} onSubmit={handleSubmit} />;
}
```

### Custom Hooks Pattern

```javascript
// apps/web-app/src/hooks/useAuth.js
import { createContext, useContext, useState, useEffect } from 'react';
import Keycloak from 'keycloak-js';
import { keycloakConfig } from '@config/keycloak.config';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [keycloak, setKeycloak] = useState(null);
  const [authenticated, setAuthenticated] = useState(false);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const kc = new Keycloak(keycloakConfig);

    kc.init({
      onLoad: 'check-sso',
      checkLoginIframe: true,
      pkceMethod: 'S256'
    }).then(authenticated => {
      setKeycloak(kc);
      setAuthenticated(authenticated);

      if (authenticated) {
        setUser({
          sub: kc.tokenParsed.sub,
          email: kc.tokenParsed.email,
          name: kc.tokenParsed.name,
          orgId: kc.tokenParsed.org_id,
          roles: kc.tokenParsed.realm_access?.roles || []
        });
      }

      setLoading(false);
    });

    // Token refresh
    kc.onTokenExpired = () => {
      kc.updateToken(30).catch(() => {
        kc.logout();
      });
    };
  }, []);

  const login = () => keycloak.login();
  const logout = () => keycloak.logout();
  const getToken = () => keycloak.token;

  return (
    <AuthContext.Provider value={{
      authenticated,
      user,
      loading,
      login,
      logout,
      getToken
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within AuthProvider');
  }
  return context;
};
```

### API Client Pattern

```javascript
// apps/web-app/src/utils/apiClient.js
import axios from 'axios';
import { useAuth } from '@hooks/useAuth';

const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:4000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// Request interceptor to add auth token
apiClient.interceptors.request.use(
  async (config) => {
    const token = await getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor for error handling
apiClient.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      // Redirect to login
      window.location.href = '/login';
    }

    const errorMessage = error.response?.data?.message || error.message;
    return Promise.reject(new Error(errorMessage));
  }
);

export default apiClient;

// Typed API methods
export const api = {
  users: {
    getProfile: (userId) => apiClient.get(`/users/${userId}`),
    updateProfile: (userId, data) => apiClient.put(`/users/${userId}`, data),
    listUsers: (orgId) => apiClient.get(`/users?org_id=${orgId}`)
  },
  organizations: {
    get: (orgId) => apiClient.get(`/organizations/${orgId}`),
    create: (data) => apiClient.post('/organizations', data),
    update: (orgId, data) => apiClient.put(`/organizations/${orgId}`, data)
  }
};
```

## Express Microservice Patterns

### Service Structure

```javascript
// services/user-service/src/index.js
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import morgan from 'morgan';
import { connectDB } from './config/database.js';
import { errorHandler } from './middleware/errorHandler.js';
import { authMiddleware } from './middleware/auth.js';
import userRoutes from './routes/users.js';

const app = express();

// Security middleware
app.use(helmet());
app.use(cors({
 

Related in Web Dev