fetch inside getInitialProps being executed client side
See original GitHub issueI have the following page, pages/article.js:
import React from 'react';
import Head from 'next/head';
import 'isomorphic-fetch';
import Page from '../layouts/gethelp.v3';
import Link from '../components/Link';
export default class extends React.Component {
static async getInitialProps () {
// eslint-disable-next-line no-undef
const res = await fetch(`https://site.com/article/27`, {
method: 'GET',
credentials: 'include',
headers: {
'Authorization': 'Basic dXNlcm5hbWU6cGFzc3dvcmQ='
}
});
const json = await res.json();
return { article: json }
}
render() {
const {
summary,
body
} = this.props.article;
return (
<Page>
<div className="container">
<h3>{summary}</h3>
<p dangerouslySetInnerHTML={{__html: body}}></p>
</div>
</Page>
);
}
}
I have an index.js page as well:
import Page from '../layouts/gethelp.v3';
import Link from '../components/Link';
export default () => (
<Page>
<div className="articles">
<h2>Articles</h2>
<hr />
<ol>
<li><Link href="/article">Article</Link></li>
</ol>
</div>
</Page>
);
When I navigate directly to /article (by typing the URL or hitting refresh on that page), the page loads fine and the fetch request is completed on the server, as I can’t see anything in the network log on the client.
However, if I’m on the index page and I click on the link pointing to /article, then I get the errors below.

If I try passing the credentials through the URL, ie; user:pass@somesite.com, then I receive the following error, showing it’s being executed on the client:
Update: Navigating directly to /article loads the content on the server and passes to the client, as expected, but navigating to / (index.js) from a link on /article and then navigating back via the browser back button causes the following errors as well.
Issue Analytics
- State:
- Created 6 years ago
- Comments:8 (2 by maintainers)
It’s not insecure to fetch data from your API client side, every piece of code in your Next.js app should be universal, that mean, always think you code is going to be executed either server and client side.
If you want to only navigate server side then use normal links (
<a>
) instead ofnext/link
, that way it’s going to reload the page, but if you do that then the usage of React doesn’t make any sense, use Django, Rails, Laravel, Express, etc. and create a simple app with server routes and pages reloads.The whole point of using React and Next.js is having a server rendered page for the first access and client rendered pages (with data fetch) for client navigation.
Okay, I understand @sergiodxa, I will move my insecure API requests into an API middle layer.