Troubleshooting Fastay.js
This guide helps you identify and fix common problems when working with Fastay.js applications.
Server Starts but Routes Don't Respond
Symptom The Fastay server starts successfully (shows listening port), but HTTP requests to your routes return 404 Not Found.
Likely Cause
- The
apiDirpath is incorrect or doesn't exist - Route files are not named
route.ts(orroute.js) - The
baseRouteconfiguration doesn't match what you're requesting
How to Resolve
-
Verify your
createAppconfiguration:await createApp({
apiDir: "./src/api", // Ensure this path exists
baseRoute: "/api", // Routes will be under /api/*
}); -
Check your file structure:
src/api/hello/route.ts → GET /api/hello
src/api/users/route.ts → GET /api/users -
Confirm route files are named exactly
route.ts(notroutes.ts,index.ts, etc.)
Route Not Being Loaded
Symptom A specific route file exists but returns 404, while other routes work.
Likely Cause
- File naming or location doesn't match expected pattern
- Dynamic route folder naming uses wrong syntax
- Route file contains syntax errors that prevent loading
How to Resolve
-
For dynamic routes, use brackets
[]:src/api/users/[id]/route.ts → GET /api/users/:id -
Check for TypeScript/JavaScript errors in the route file
-
Verify the file exports HTTP methods correctly:
// Must export functions named after HTTP methods
export async function GET(request: Request) {
return { message: "Hello" };
}
Middleware Not Executed
Symptom Middleware functions are defined but don't run for requests.
Likely Cause
- Middleware not registered in
middleware.ts - Route pattern doesn't match the requested path
- Middleware file not in
src/middlewares/directory - Middleware doesn't call
next()or sends a response
How to Resolve
-
Ensure middleware is registered in
src/middlewares/middleware.ts:import { createMiddleware } from "@syntay/fastay";
import { auth } from "./auth";
export const middleware = createMiddleware({
"/api/protected": [auth], // Apply to /api/protected
"/": [logger], // Apply to all routes
}); -
Verify middleware calls
next()to continue the chain
Request Body is Undefined
Symptom
await request.body returns undefined or empty object.
Likely Cause
- Not awaiting
request.body(it returns a Promise) - Missing
Content-Type: application/jsonheader - Body size exceeds parser limits
- Using wrong method to access body (FormData vs JSON)
How to Resolve
-
Always await the body:
// ✗ Wrong
const data = request.body;
// ✓ Correct
const data = await request.body; -
For JSON requests, include proper headers:
// Client-side fetch
fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "John" }),
}); -
For FormData/File uploads, use
formData()method:const formData = await request.formData();
const file = formData.get("avatar") as File;
CORS Errors in Browser
Symptom Browser shows CORS errors when calling your API from a different origin.
Likely Cause
- CORS not configured in Fastay
- Frontend and backend on different ports/domains
- Missing credentials configuration
How to Resolve
-
Configure CORS in your
createApp:await createApp({
enableCors: {
allowAnyOrigin: process.env.NODE_ENV === "development",
credentials: true,
methods: "GET,POST,PUT,DELETE,OPTIONS",
},
}); -
For production, specify allowed origins:
enableCors: {
allowAnyOrigin: false,
cookieOrigins: [
'https://yourdomain.com',
'https://app.yourdomain.com'
]
} -
Ensure frontend includes credentials if using cookies:
fetch("/api/data", {
credentials: "include", // For cookies/auth
});
Environment Variables Not Loading
Symptom
process.env values are undefined in your Fastay application.
Likely Cause
.envfile not loaded- Wrong variable names
- Environment variables set after app initialization
How to Resolve
-
Load dotenv early in your entry file:
// src/index.ts
import "dotenv/config"; // Load .env before anything else
import { createApp } from "@syntay/fastay";
void (async () => {
await createApp({
/* config */
});
})(); -
Check
.envfile location (should be in project root) -
Verify variable names match:
# .env file
DATABASE_URL=postgresql://...
JWT_SECRET=your-secret-key -
For production, ensure variables are set in your hosting environment
"Slow Request Detected" Warning
Symptom
Console shows warnings like Slow request detected: /api/users took 1250ms.
Likely Cause
- Database queries taking too long
- External API calls without timeouts
- Complex business logic in route handlers
- Large data processing without streaming
How to Resolve
-
Check database query performance:
// Add indexes, optimize queries
const users = await db.users.findMany({
where: { active: true },
take: 100, // Limit results
}); -
Add timeouts to external requests:
const response = await fetch("https://api.example.com/data", {
signal: AbortSignal.timeout(5000), // 5 second timeout
}); -
Move heavy processing to background jobs or services
-
Consider streaming large responses:
return {
stream: createReadStream("/large/file.csv"),
headers: { "Content-Type": "text/csv" },
};
File Upload Not Working
Symptom
File uploads fail or request.formData() throws errors.
Likely Cause
- Missing
enctype="multipart/form-data"in form - File size exceeds limits
- Wrong method to access uploaded files
- Temporary storage permissions
How to Resolve
-
Ensure proper form encoding:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="document" />
</form> -
Use
formData()method in your route:export async function POST(request: Request) {
const formData = await request.formData();
const file = formData.get("document") as File;
// File properties
console.log(file.name, file.size, file.type);
} -
Check file object is not null:
const file = formData.get("document") as File;
if (!file || file.size === 0) {
return { status: 400, body: { error: "No file uploaded" } };
}
Differences Compared to Express Behavior
Symptom Code that works in Express doesn't work in Fastay, or behaves differently.
Key Differences to Remember
-
Route Registration
// Express: Manual registration
app.get('/api/users', handler);
// Fastay: Automatic from file structure
// File: src/api/users/route.ts
export async function GET(request: Request) { ... } -
Middleware Registration
// Express: app.use() or route-specific
app.use("/api", middleware);
// Fastay: Configured in middleware.ts
export const middleware = createMiddleware({
"/api": [myMiddleware],
}); -
Response Handling
// Express: Explicit response methods
res.status(201).json({ data });
// Fastay: Return values or objects
return { status: 201, body: { data } };
// Or simply: return { data }; -
Error Handling
// Express: Custom error middleware
app.use((err, req, res, next) => { ... });
// Fastay: Through expressOptions
await createApp({
expressOptions: {
errorHandler: (err, req, res, next) => { ... }
}
});
How to Adapt
- Follow Fastay's file-based conventions
- Use return values instead of
res.json()in simple cases - Configure middleware through the middleware system
- Access request body with
await request.body
Common Configuration Issues
Port Already in Use
Symptom: Error: listen EADDRINUSE: address already in use :::3000
Solution:
// Change port
await createApp({ port: 5000 });
// Or find available port automatically
await createApp({ port: 0 }); // Fastay will choose a port
TypeScript Compilation Errors
Symptom: Server won't start with TypeScript errors.
Solution:
-
Run TypeScript compiler separately first:
npx tsc --noEmit # Check for errors
Hot Reload Not Working
Symptom: Changes to route files require server restart.
Solution:
-
Use development mode with file watching:
npm run dev:watch # If configured -
Ensure you're editing files in
src/api/directory -
Check that your development setup monitors the correct directories
Getting More Help
If you encounter issues not covered here:
-
Check Application Logs
- Look for error messages in console output
- Check for stack traces pointing to specific files
-
Verify Configuration
- Compare with working examples from Fastay documentation
- Ensure all required options are provided to
createApp
-
Simplify to Isolate
- Create a minimal test case with just the problematic feature
- Remove middleware and complex logic to identify the root cause
-
Review Fastay Examples
- Refer to example projects in Fastay repository
- Check similar use cases in the documentation
Fastay aims to provide clear error messages when possible. Most issues can be resolved by checking configuration, file structure, and ensuring you're following Fastay's conventions rather than Express patterns.