TL;DR
Railway gives you automatic SSL and managed infrastructure, so the work left to you is narrower. Keep secrets in environment variables, which are stored securely but readable by any code in the service. Put your database on private networking when you can, and put authentication in front of your services. Private networking keeps database traffic off the public internet.
What Railway Handles for You
A fair amount comes built in:
- Automatic SSL: All services get HTTPS by default
- Isolated containers: Each service runs in its own container
- Private networking: Services can communicate internally
- Managed databases: PostgreSQL, MySQL, Redis with backups
- Encrypted secrets: Environment variables are encrypted at rest
Environment Variables on Railway
Railway stores your variables and injects them when the service runs. There are three kinds:
Setting Variables
- Shared variables: Defined once at the project level, then shared into each service that needs them (a service doesn't see one until you share it)
- Service variables: Specific to one service
- Reference variables: Automatically connect services (like database URLs)
// Node.js
const databaseUrl = process.env.DATABASE_URL;
const apiSecret = process.env.API_SECRET;
// Python
import os
database_url = os.environ.get('DATABASE_URL')
api_secret = os.environ.get('API_SECRET')
Never hardcode secrets: Your Railway code is private, but use environment variables anyway. Rotation gets easier, and a secret can't leak through logs or version control if it was never in the code.
Database Security on Railway
Use Private Networking
Railway can provision databases that are reachable only over its private network:
# Public URL (accessible from internet)
DATABASE_URL=postgres://user:pass@roundhouse.proxy.rlwy.net:5432/railway
# Private URL (internal only, more secure)
DATABASE_PRIVATE_URL=postgres://user:pass@postgres.railway.internal:5432/railway
If your app and database both live on Railway, use the private URL. The traffic never touches the public internet.
Database Security Checklist
PostgreSQL Security on Railway
Use private networking URL if possible
Strong, unique password (Railway generates these)
Don't expose database port publicly unless needed
Enable SSL for external connections
Regular backups (Railway does this automatically)
Consider row-level security for multi-tenant apps
Service Security
Protecting API Endpoints
// Express.js example with authentication
const express = require('express');
const app = express();
// Rate limiting
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per window
});
app.use(limiter);
// Authentication middleware
const authenticate = async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const user = await verifyToken(token);
req.user = user;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
// Protected routes
app.get('/api/user', authenticate, (req, res) => {
res.json({ user: req.user });
});
// Health check (no auth needed)
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
Internal Service Communication
Private networking doesn't mean you can skip auth between services. Calls inside the network should still carry a token:
// Use private networking for internal calls
const INTERNAL_API = process.env.API_PRIVATE_URL || 'http://api.railway.internal';
// Still authenticate internal requests
const response = await fetch(`${INTERNAL_API}/internal/process`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.INTERNAL_SERVICE_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
Deployment Security
Preview Environments
Railway can spin up a preview environment for each PR. That's handy. It's also an easy way to point test code at production data:
- Preview environments use the same environment variables by default
- Consider using different database instances for previews
- Don't connect preview environments to production data
Deploy Configurations
[build]
builder = "NIXPACKS"
[deploy]
startCommand = "node server.js"
healthcheckPath = "/health"
healthcheckTimeout = 300
# Useful for security
restartPolicyType = "ON_FAILURE"
restartPolicyMaxRetries = 3
Logging and Monitoring
Secure Logging Practices
// DON'T log sensitive data
console.log('User login:', { email, password }); // BAD!
// DO log safely
console.log('User login:', { email, passwordProvided: !!password }); // OK
// Use a logger that can redact sensitive fields
const logger = createLogger({
redact: ['password', 'token', 'secret', 'authorization']
});
logger.info('Request received', {
path: req.path,
headers: req.headers // Authorization will be redacted
});
Railway Security Checklist
Before Going to Production
All secrets in environment variables
Database using private networking
API endpoints have authentication
Rate limiting configured
Health check endpoint exists
Logs don't contain sensitive data
Preview environments don't use production data
CORS configured appropriately
Are my environment variables secure on Railway?
Yes. Railway encrypts environment variables at rest and injects them securely at runtime. They're not visible in logs or to other users. Any code running in your service can read them, though, so be careful what you deploy.
Should I use private or public database URLs?
Use the private URL when your app and database are both on Railway, since the traffic stays inside Railway's network. Save the public URL for when you genuinely need outside access, like from your laptop during development.
How do I rotate secrets on Railway?
Change the variable in Railway's dashboard and redeploy. The new value is live as soon as the deploy finishes. Don't forget the other half: revoke or rotate the credential with the provider that issued it.
Can other Railway users access my services?
No. Your services are isolated, and other Railway users can't reach your private network, databases, or environment variables. Public endpoints are a different story: anyone can hit them unless you add authentication.
Deploying to Railway?
Scan your project for security issues before going live.