使用getServerSideProps获取数据时遭遇Server Error SyntaxError: Unexpected token 'export'问题求助
Let's break down this issue you're hitting and walk through the most likely fixes—this error usually stems from mismatched routing patterns, untranspiled dependencies, or environment compatibility problems.
1. Check Your Page's Directory (Next.js 13 Router Conflict)
Next.js 13 introduced the App Router (default for new projects, using the app/ folder) which doesn't support getServerSideProps—that's a feature exclusive to the older Pages Router (using the pages/ folder).
If you placed search.js in the app/ directory, Next.js will try to parse it as an App Router component, and the export async function getServerSideProps() syntax will throw an unexpected token error.
Fix:
- Move
search.jsto the root-levelpages/folder (create it if it doesn't exist). Next.js will automatically switch to Pages Router mode for that file. - If you want to use App Router instead, replace
getServerSidePropswith App Router's native data fetching: since App Router components are Server Components by default, you can fetch data directly in the component withasync/await:
async function Search() { const searchResults = await fetch("https://www.jsonkeeper.com/b/W528").then(res => res.json()); // rest of your component code } export default Search;
2. Fix Untranspiled Third-Party Dependencies
Your package.json includes next-transpile-modules, which is used to convert non-ES-module dependencies into code Node.js can parse on the server. If a dependency like react-date-range or date-fns ships untranspiled ES syntax (like export), Node.js will throw this error when trying to run it server-side.
Fix:
- Make sure you've configured
next-transpile-modulescorrectly innext.config.js(create this file if it doesn't exist):
const withTM = require('next-transpile-modules')(['react-date-range', 'date-fns']); module.exports = withTM({ // Add any other Next.js config options here });
- If that doesn't work, try upgrading your dependencies to newer versions—older packages like
react-date-range@1.4.0may have better ES module support in later releases (e.g.,^2.0.0).
3. Verify Your Fetch Response
While less likely, it's possible the URL you're fetching isn't returning valid JSON. If the response includes JavaScript export syntax (instead of pure JSON), parsing it will fail.
Fix:
Test the API directly in your terminal to confirm it returns valid JSON:
curl https://www.jsonkeeper.com/b/W528
If the output includes export or other non-JSON code, you'll need to use a different data source.
4. Check Node.js Version Compatibility
Next.js 13 requires Node.js 16.8 or higher. Older versions of Node.js don't fully support modern ES module syntax, which can lead to unexpected token errors.
Fix:
Run node -v in your terminal to check your version. If it's below 16.8, upgrade to the latest LTS version (18.x or 20.x are recommended).
内容的提问来源于stack exchange,提问作者noClue93

