Resolving a Strapi 404 error requires verifying that the backend server is running, checking route definitions in your controllers, and ensuring your frontend requests match the correct API paths. This guide walks you through diagnosing connection issues, validating endpoint configurations, and fixing common misconfigurations to restore data fetching functionality.
Verifying Server Connectivity
The most immediate cause of a "Resource not found" status is a simple connectivity failure between your client application and the Strapi backend. Before diving into code-level debugging, you must confirm that the server process is active and listening on the expected port. If the server is down, any request will fail, often resulting in a network error or a generic 404 depending on how your proxy or load balancer handles the downtime. Start by opening your terminal and navigating to your project root. Run the commandnpm run develop or yarn develop to start the development server. Watch the console output for the line indicating that the server has started. It typically looks like this: [200ms] http://localhost:1337/admin. If you see this message, the server is up. If you encounter an error such as a port conflict or database connection failure, resolve those first, as they prevent the API from serving any routes.
Next, test the connectivity directly using a tool like cURL or Postman. Send a GET request to http://localhost:1337/health. A healthy Strapi instance should return a JSON response with a status of "ok". If this endpoint returns a 404, there is a fundamental configuration issue with your Strapi setup, possibly related to environment variables or core plugins. If the health check passes but your custom endpoints still fail, the issue lies within your specific route definitions rather than general server availability.
For more complex deployments involving Docker or cloud hosting, ensure that the container ports are correctly mapped. If you are using Docker Compose, verify that ports: ["1337:1337"] is present in your service definition. Misconfigured networking can also lead to 404s if the internal DNS resolution fails to reach the API service. In these cases, check your container logs using docker logs <container_id> to identify any startup failures.
Checking Route Definitions and Controllers
Strapi generates RESTful endpoints automatically based on your content types, but custom routes require explicit configuration. If you are trying to fetch data from a standard content type like "articles", the default endpoint is/api/articles. However, if you have created a custom controller or modified the default behavior, the path may differ. A common mistake is assuming that all endpoints follow the standard pluralized format without checking for overrides.
Navigate to the src/api/<content-type-name>/controllers directory in your project structure. Inspect the JavaScript file associated with your content type. Ensure that the export object contains the methods you are trying to call. For example, if you are calling find, verify that the controller exports a function named find. If the method is missing or misspelled, Strapi will not recognize the route, leading to a 404 error.
If you are using custom routes defined in src/config/routes.json, open this file and review the entries. The structure should map a URL path to a specific controller action. For instance:
{
"method": "GET",
"path": "/custom-endpoint",
"handler": "MyController.myAction",
"config": {
"policies": []
}
}
Ensure that the path matches exactly what your frontend is requesting, including trailing slashes. Strapi’s router is strict about path matching. Also, verify that the handler string correctly references the controller name and method, separated by a dot. Typos here are a frequent source of persistent 404 errors that are difficult to debug because the server appears to be running correctly.
Additionally, check if any policies or middlewares are blocking access. While policies usually return 401 (Unauthorized) or 403 (Forbidden), misconfigured middleware can sometimes intercept requests and drop them silently or redirect them incorrectly. Review the src/middlewares folder to ensure no custom middleware is interfering with your API calls.
Validating Frontend Request Configuration
Even with a perfectly configured backend, your frontend application might send requests in a way that Strapi cannot understand. This is particularly common when using frameworks like React, Vue, or Angular. One frequent issue is incorrect base URL configuration. If your frontend is hosted on a different domain or subdomain than your Strapi backend, you must ensure that the API base URL includes the correct protocol and port. Check your environment variables or configuration files where the API URL is defined. It should look something likeprocess.env.REACT_APP_API_URL = "http://localhost:1337". Avoid appending extra slashes or omitting the port number. When constructing your fetch or axios calls, concatenate the base URL with the endpoint path carefully. For example:
const response = await fetch(`${API_URL}/api/articles`);
Notice the absence of double slashes. Using ${API_URL}//api/articles can cause routing issues in some browsers or proxies.
Another critical aspect is HTTP headers. Strapi expects certain headers for authentication and content negotiation. If you are sending authenticated requests, ensure you are including the Authorization header with the Bearer token. Missing or malformed tokens can sometimes result in unexpected error codes depending on your security policies. Additionally, verify that your Content-Type header is set to application/json if you are sending data in the request body, although this primarily affects POST and PUT requests.
CORS (Cross-Origin Resource Sharing) settings can also masquerade as 404 errors in browser developer tools. If CORS is misconfigured, the browser might block the response entirely, making it appear as if the resource was not found. Check your src/config/middlewares.js file to ensure that the strapi::cors middleware is enabled and configured to allow your frontend’s origin. Setting origin: ['http://localhost:3000'] allows requests from your local development server.
Clearing Cache and Restarting Services
After making changes to your controllers, routes, or configuration files, Strapi does not always reflect these changes immediately due to caching mechanisms. In development mode, hot reloading should handle most updates, but sometimes the cache becomes stale, especially after modifying core configurations or adding new plugins. A simple restart of the development server can clear these caches and reload the route definitions. Stop the current server process by pressingCtrl+C in your terminal. Then, delete the .cache folder if it exists in your project root. This folder stores temporary build artifacts and cached module resolutions. After deleting it, restart the server with npm run develop. This forces Strapi to rebuild its internal routing table and re-evaluate all controllers and policies.
If you are using a production build, ensure that you have rebuilt the application after making changes. Running npm run build followed by npm run start ensures that the latest code is compiled and served. In production environments, consider clearing the CDN cache if you are serving assets through a content delivery network, as old versions of your API documentation or static resources might be cached.
For advanced troubleshooting, enable verbose logging by setting the DEBUG environment variable to strapi:*. This provides detailed information about each request processed by Strapi, including which router matched the URL and which controller was invoked. This level of detail is invaluable when identifying subtle mismatches between your frontend requests and backend configurations.
Frequently Asked Questions
Why does my custom endpoint work in Postman but not in the browser?
This is almost always a CORS issue. Your browser blocks the request due to security policies, while Postman ignores them. Configure thestrapi::cors middleware in src/config/middlewares.js to include your frontend’s origin URL.
How do I know if my controller method is exported correctly?
Check that your controller file exports an object with the method name as a key. For example,module.exports = { find: async () => {} }. If the method is not exported, Strapi cannot bind it to a route, resulting in a 404.
Can environment variables cause a 404 error?
Yes, if your API URL or database connection strings are incorrect, the server might fail to initialize properly or route requests to the wrong handler. Always verify that your .env file is loaded correctly by checking the server logs during startup.What should I do if I get a 404 after deploying to production?
Ensure that you have rebuilt your application usingnpm run build. Production servers serve static files and do not use hot reloading. Also, verify that the Nginx or Apache proxy settings forward requests to the correct Strapi port.