Cyberbezpieczeństwo dla stron - Jak chronić się przed atakami w 2026?

Każde 39 sekund dochodzi do cyberataku. 43% ataków to małe firmy. 60% firm bankrutuje w ciągu 6 miesięcy po dużym ataku.
Cyberbezpieczeństwo to nie paranoja. To konieczność.
Najpopularniejsze ataki na strony (2026)
1. SQL Injection
Jak działa:
Hacker wstrzykuje złośliwy kod SQL przez formularz.
Przykład:
-- Input użytkownika: admin' OR '1'='1
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'xxx'
-- Zwraca wszystkich userów!
Obrona:
// ŹLE (vulnerable)
const query = `SELECT * FROM users WHERE email = '${email}'`;
// DOBRZE (prepared statements)
const query = "SELECT * FROM users WHERE email = ?";
await db.query(query, [email]);
// NAJLEPIEJ (ORM)
const user = await prisma.user.findUnique({
where: { email: email },
});
2. Cross-Site Scripting (XSS)
Jak działa:
Wstrzyknięcie JavaScript przez input użytkownika.
Przykład:
alert('hacked') --> {userInput}
Obrona w React/Next.js:
// React auto-escapes (bezpieczne)
{
userInput;
}
// ŹLE (dangerous)
// DOBRZE (sanitize)
import DOMPurify from "isomorphic-dompurify";
3. Cross-Site Request Forgery (CSRF)
Jak działa:
Hacker zmusza użytkownika do wykonania akcji bez jego wiedzy.
Obrona:
// Użyj CSRF tokens
import { csrf } from "@/lib/csrf";
// Generuj token
export async function GET() {
const token = await csrf.generate();
return Response.json({ csrfToken: token });
}
// Waliduj token
export async function POST(request: Request) {
const token = request.headers.get("x-csrf-token");
if (!(await csrf.verify(token))) {
return Response.json({ error: "Invalid CSRF token" }, { status: 403 });
}
// Process request
}
Next.js middleware:
// middleware.ts
import { csrf } from "./lib/csrf";
export async function middleware(request: NextRequest) {
if (request.method === "POST") {
const token = request.headers.get("x-csrf-token");
if (!(await csrf.verify(token))) {
return new Response("Forbidden", { status: 403 });
}
}
return NextResponse.next();
}
4. DDoS (Distributed Denial of Service)
Jak działa:
Tysiące requestów naraz, serwer pada.
Obrona:
1. Rate Limiting:
// app/api/contact/route.ts
import { rateLimit } from "@/lib/rate-limit";
export async function POST(request: Request) {
const ip = request.headers.get("x-forwarded-for");
const { success } = await rateLimit.check(ip, {
limit: 5, // 5 requests
window: 60000, // per minute
});
if (!success) {
return Response.json({ error: "Too many requests" }, { status: 429 });
}
// Process request
}
2. CDN/WAF (Web Application Firewall):
- Cloudflare (automatic DDoS protection)
- Vercel Edge (built-in protection)
- AWS CloudFront + WAF
5. Brute Force Attacks
Jak działa:
Próba zgadnięcia hasła przez tysiące prób.
Obrona:
// Login endpoint z rate limiting
export async function POST(request: Request) {
const { email, password } = await request.json();
const ip = request.headers.get("x-forwarded-for");
// Rate limit: 5 prób / 15 minut
const attempts = await redis.get(`login:${ip}`);
if (attempts >= 5) {
return Response.json(
{ error: "Too many login attempts. Try again in 15 minutes." },
{ status: 429 },
);
}
await redis.incr(`login:${ip}`);
await redis.expire(`login:${ip}`, 900); // 15 min
// Validate credentials
const user = await validateUser(email, password);
if (!user) {
return Response.json({ error: "Invalid credentials" }, { status: 401 });
}
// Clear attempts on success
await redis.del(`login:${ip}`);
return Response.json({ success: true });
}
6. Session Hijacking
Jak działa:
Przejęcie sesji użytkownika (cookie theft).
Obrona:
// Cookie security flags
import { cookies } from "next/headers";
export async function POST() {
const cookieStore = await cookies();
cookieStore.set("session", token, {
httpOnly: true, // Nie dostępne dla JS
secure: true, // Tylko HTTPS
sameSite: "strict", // CSRF protection
maxAge: 3600, // 1 hour
path: "/",
});
}
Security Headers - Must Have
// next.config.js
module.exports = {
async headers() {
return [
{
source: "/:path*",
headers: [
{
key: "X-Frame-Options",
value: "DENY", // Prevent clickjacking
},
{
key: "X-Content-Type-Options",
value: "nosniff", // Prevent MIME sniffing
},
{
key: "X-XSS-Protection",
value: "1; mode=block", // XSS protection
},
{
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubDomains; preload", // Force HTTPS
},
{
key: "Content-Security-Policy",
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self'",
"connect-src 'self'",
].join("; "),
},
{
key: "Referrer-Policy",
value: "strict-origin-when-cross-origin",
},
{
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=()",
},
],
},
];
},
};
Environment Variables Security
ŹLE:
// Exposed to client!
const apiKey = process.env.NEXT_PUBLIC_API_KEY;
DOBRZE:
// Server-only
const apiKey = process.env.API_KEY; // No NEXT_PUBLIC_ prefix
// Use in API route
export async function POST() {
const apiKey = process.env.API_KEY; // Safe
// ...
}
Best practice:
# .env.local (never commit!)
DATABASE_URL="postgresql://..."
API_SECRET="xxx"
STRIPE_SECRET_KEY="sk_test_xxx"
# Only NEXT_PUBLIC_ vars are exposed to client
NEXT_PUBLIC_API_URL="https://api.example.com"
Input Validation & Sanitization
// Użyj Zod dla validation
import { z } from "zod";
const contactSchema = z.object({
name: z.string().min(2).max(50),
email: z.string().email(),
message: z.string().min(10).max(1000),
phone: z
.string()
.regex(/^\+?[1-9]\d{1,14}$/)
.optional(),
});
export async function POST(request: Request) {
const body = await request.json();
// Validate
const result = contactSchema.safeParse(body);
if (!result.success) {
return Response.json(
{ error: "Invalid input", details: result.error.errors },
{ status: 400 },
);
}
const { name, email, message } = result.data;
// Safe to use
await sendEmail({ name, email, message });
return Response.json({ success: true });
}
Authentication Best Practices
1. Use proper auth libraries
// NextAuth.js (recommended)
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days
},
callbacks: {
async jwt({ token, account }) {
if (account) {
token.accessToken = account.access_token;
}
return token;
},
},
};
export default NextAuth(authOptions);
2. Password hashing
import bcrypt from "bcryptjs";
// Hashing
const hashedPassword = await bcrypt.hash(password, 12);
// Verification
const isValid = await bcrypt.compare(password, hashedPassword);
3. 2FA (Two-Factor Authentication)
import speakeasy from "speakeasy";
import QRCode from "qrcode";
// Generate secret
const secret = speakeasy.generateSecret({
name: "YourApp ([email protected])",
});
// Generate QR code
const qrCodeUrl = await QRCode.toDataURL(secret.otpauth_url);
// Verify token
const verified = speakeasy.totp.verify({
secret: secret.base32,
encoding: "base32",
token: userToken,
});
Dependency Security
1. Regular updates
# Check for vulnerabilities
npm audit
# Fix automatically
npm audit fix
# Force fix (może złamać compatibility)
npm audit fix --force
2. Use Snyk or Dependabot
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
3. Avoid suspicious packages
# Check package before installing
npx socket npm i package-name
# Shows security, maintenance, quality scores
HTTPS & SSL/TLS
Must-have w 2026:
- ✅ SSL certificate (Let's Encrypt free)
- ✅ HTTPS redirect (force)
- ✅ HSTS header
- ✅ TLS 1.3
Vercel/Netlify: Automatic HTTPS ✅
Custom server:
# nginx.conf
server {
listen 80;
server_name yoursite.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yoursite.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.3;
# ...
}
Backup Strategy
3-2-1 Rule:
- 3 copies of data
- 2 different media types
- 1 off-site backup
# Automated daily backups
# Database
pg_dump database_name > backup-$(date +%Y%m%d).sql
# Files
tar -czf backup-$(date +%Y%m%d).tar.gz /var/www/html
# Upload to S3
aws s3 cp backup-$(date +%Y%m%d).tar.gz s3://bucket/backups/
Security Checklist
✅ HTTPS enforced
✅ Security headers configured
✅ Input validation (all forms/APIs)
✅ SQL Injection protection (prepared statements)
✅ XSS protection (sanitize HTML)
✅ CSRF tokens
✅ Rate limiting (APIs, login)
✅ Secure cookies (httpOnly, secure, sameSite)
✅ Environment variables (never commit .env)
✅ Dependencies updated (npm audit)
✅ Authentication library (NextAuth, Auth0)
✅ Password hashing (bcrypt, argon2)
✅ 2FA option
✅ WAF/CDN (Cloudflare, Vercel)
✅ Regular backups
✅ Monitoring & logging
Tools & Resources
Scanning:
Monitoring:
- Sentry (error tracking)
- LogRocket (session replay + security)
- Cloudflare Analytics
Libraries:
- helmet.js (security headers)
- rate-limiter-flexible
- joi / zod (validation)
Podsumowanie
Security to nie opcja. To fundament każdej strony w 2026. Jeden atak może kosztować Cię biznes, reputację, i prawnie - RODO kary idą w miliony.
W Netova każdy projekt przechodzi security audit. HTTPS, headers, validation, rate limiting - to wszystko standard.