Skip to content

Instantly share code, notes, and snippets.

@ayoubzulfiqar
Last active July 31, 2025 13:57
Show Gist options
  • Save ayoubzulfiqar/2e328039e5769f18536343db04f04c7f to your computer and use it in GitHub Desktop.
Save ayoubzulfiqar/2e328039e5769f18536343db04f04c7f to your computer and use it in GitHub Desktop.
ShouldHide and DO at the END

You cannot completely hide files like .tsx source code or JSON responses from users who have access to browser developer tools, but you can make them much harder to access and understand. Here are practical approaches:


1. For TypeScript/TSX Files

A. Build and Bundle Your Code

  • Why: Raw .tsx files exist only during development. In production, they should be compiled to JavaScript and bundled.
  • How:
    # Example with Create React App
    npm run build
    
    # Example with Vite
    npm run build
    
    # Example with Webpack
    webpack --mode production
  • Result: Users see only minified/bundled JS files like main.abc123.js instead of your source .tsx files.

B. Minify and Obfuscate JavaScript

  • Why: Makes the bundled code extremely difficult to read and reverse-engineer.
  • How:
    • Use tools like Terser, UglifyJS, or built-in minifiers in your build tool.
    • Example Webpack config:
      const TerserPlugin = require('terser-webpack-plugin');
      
      module.exports = {
        optimization: {
          minimize: true,
          minimizer: [new TerserPlugin({
            terserOptions: {
              mangle: true, // Shortens variable names
              compress: true, // Compresses code
            },
          })],
        },
      };

C. Use Source Maps Only in Development

  • Why: Source maps help browsers map minified code back to original source code.
  • How:
    // In production webpack config
    devtool: 'hidden-source-map' // or false

2. For JSON API Responses

A. Don't Expose Sensitive Data in Responses

  • Why: The biggest issue isn't that JSON is visible, but what's in the JSON.
  • How:
    // ❌ Bad - Exposing internal data
    res.json({
      id: 123,
      name: "John",
      password: "secret123", // Never do this!
      ssn: "123-45-6789",
      role: "admin"
    });
    
    // ✅ Good - Only send necessary data
    res.json({
      id: 123,
      name: "John"
    });

B. Use API Gateways or Backend Proxies

  • Why: Hide your actual API structure from the frontend.
  • How:
    // Instead of calling external API directly
    // Frontend calls your backend
    // Frontend → Your Server → External API
    // Your server processes and sanitizes the response

C. Implement Response Compression

  • Why: Makes raw JSON harder to read in Network tab.
  • How:
    // Express.js example
    const compression = require('compression');
    app.use(compression());

D. Use Generic Endpoint Names

  • Why: Don't reveal what the API does in the URL.
  • How:
    // ❌ Bad - Reveals too much
    GET /api/getUserPrivateData?userId=123
    
    // ✅ Better - More generic
    GET /api/data/123

3. Additional Hardening Techniques

A. Disable Right-Click and Developer Tools (Limited Effectiveness)

// Basic prevention (easily bypassed)
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', event => {
  if (event.key === 'F12' || 
      (event.ctrlKey && event.shiftKey && event.key === 'I')) {
    event.preventDefault();
  }
});

⚠️ Note: This only deters casual users, not determined attackers.

B. Server-Side Rendering (SSR)

  • Why: Render sensitive parts on the server so they never reach the client.
  • How: Use frameworks like Next.js, Nuxt.js:
    // Next.js getServerSideProps
    export async function getServerSideProps() {
      const data = await fetchSensitiveData(); // Server-side call
      return { props: { data } };
    }

C. Code Splitting and Dynamic Imports

  • Why: Load only necessary code chunks, making reverse engineering harder.
  • How:
    // Dynamic import
    const Component = await import('./SensitiveComponent');

4. What You CANNOT Hide Completely

Even with all these measures:

  • Network requests will still show in the Network tab
  • Bundled JavaScript can be reverse-engineered (though it's very difficult)
  • Determined attackers can use tools like Burp Suite, Postman, or custom scripts

5. Best Practices Summary

  1. Always build for production (never deploy development code)
  2. Minify and obfuscate all JavaScript
  3. Remove source maps from production
  4. Never send sensitive data to the client
  5. Use generic API endpoints
  6. Implement proper authentication/authorization
  7. Consider SSR for sensitive data
  8. Use HTTPS to encrypt data in transit

The issue you're describing is that sensitive information, such as API endpoints, tokens, or other data, is being exposed through the browser's Network tab. This is a common concern in web development, especially when dealing with client-side applications. Below, I will outline the key points and strategies to mitigate this exposure:


1. Understand the Nature of Client-Side Applications

  • Client-side visibility: All assets, scripts, and network requests made by a client-side application (e.g., React, Angular, Vue) are inherently visible to the user because they run in the browser.
  • Network tab inspection: The Network tab in developer tools shows all HTTP/HTTPS requests, including API calls, WebSocket connections, and other resources loaded by the application.

2. Identify Sensitive Information

Before addressing the issue, identify what specific information is being exposed:

  • API endpoints: URLs of your backend services.
  • Tokens: Authentication tokens (e.g., JWTs, session tokens).
  • Data payloads: Sensitive data sent in request bodies or query parameters.
  • Headers: Authorization headers or custom headers containing sensitive information.

3. Mitigation Strategies

While you cannot completely hide network activity from users who have access to developer tools, you can采取以下措施来减少敏感信息的暴露风险:

3.1. Use HTTPS

  • Why: Ensure all communication between the client and server is encrypted using HTTPS. This prevents man-in-the-middle attacks and ensures that intercepted traffic is not readable.
  • How: Deploy your application behind an HTTPS-enabled server (e.g., using SSL/TLS certificates).

3.2. Avoid Hardcoding Secrets

  • Why: Hardcoding sensitive information (e.g., API keys, tokens) in client-side code makes it easily accessible to anyone inspecting the source code.
  • How:
    • Store sensitive information on the server-side.
    • Use environment variables for configuration.
    • Use secure APIs that do not expose sensitive credentials.

3.3. Implement Token-Based Authentication

  • Why: Traditional session-based authentication stores session IDs in cookies, which can be vulnerable to CSRF attacks. Token-based authentication (e.g., JWT) is more secure when implemented correctly.
  • How:
    • Use short-lived tokens with expiration times.
    • Store tokens securely (e.g., in HttpOnly cookies or local storage).
    • Use the Authorization header to send tokens instead of query parameters.

3.4. Use Environment Variables for Development

  • Why: During development, avoid exposing sensitive information in source code.
  • How:
    • Use .env files to store environment-specific variables.
    • Use tools like dotenv to load these variables into your application.

3.5. Minify and Obfuscate Code

  • Why: Minifying and obfuscating your JavaScript code makes it harder for attackers to read and understand the source code.
  • How:
    • Use build tools like Webpack, Rollup, or Vite with minification plugins.
    • Use obfuscation tools (e.g., UglifyJS, Terser) to rename variables and functions.

3.6. Validate and Sanitize Inputs

  • Why: Ensure that any data sent to the server is validated and sanitized to prevent injection attacks.
  • How:
    • Implement input validation on both the client and server sides.
    • Use libraries or frameworks that provide built-in validation mechanisms.

3.7. Use Content Security Policy (CSP)

  • Why: CSP helps prevent cross-site scripting (XSS) and other code injection attacks by specifying which sources are allowed to load content.
  • How:
    • Configure a strict CSP policy in your server response headers.
    • Allow only trusted domains for loading scripts, styles, and other resources.

3.8. Limit Exposure of API Endpoints

  • Why: Reduce the surface area of attack by minimizing the exposure of API endpoints.
  • How:
    • Use proxy servers or API gateways to abstract your backend services.
    • Implement rate limiting and IP whitelisting on your backend to prevent unauthorized access.

3.9. Use Server-Side Rendering (SSR) or Static Site Generation (SSG)

  • Why: SSR and SSG render parts of your application on the server, reducing the amount of client-side code and data exposed to users.
  • How:
    • Use frameworks like Next.js (for SSR/SSG) or Nuxt.js.
    • Render sensitive components or data on the server before sending them to the client.

3.10. Educate Users

  • Why: While technical measures are essential, educating users about the risks of tampering with developer tools can also help.
  • How:
    • Include disclaimers or warnings in your application about the potential risks of modifying browser behavior.
    • Encourage users to report suspicious activities.

4. Best Practices Summary

  1. Encrypt all traffic using HTTPS.
  2. Avoid hardcoding secrets in client-side code.
  3. Use token-based authentication with short-lived tokens.
  4. Minify and obfuscate client-side code.
  5. Implement CSP to protect against XSS attacks.
  6. Validate and sanitize inputs on both client and server sides.
  7. Limit exposure of API endpoints using proxies or gateways.
  8. Consider SSR/SSG to reduce client-side exposure.
  9. Educate users about the risks of tampering with developer tools.

5. Conclusion

While you cannot completely hide network activity from users with access to developer tools, you can significantly reduce the risk of sensitive information exposure by following the above strategies. Focus on securing your backend, minimizing client-side exposure, and implementing robust security practices throughout your application.

If you have specific concerns or need further clarification on any of these points, feel free to ask!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment