This is a Next.js project bootstrapped
with create-next-app
.
by Vladilen Minin
npx create-next-app next-test
cd next-test
npm install sass
npm install -g json-server
json-server db.json -w -p 3030 -d 450
npm i -D concurrently
In common case SSR doesn't work:
export default function Posts() {
const [posts, setPosts] = useState()
useEffect(() => {
async function load() {
const response = await fetch('http://localhost:3030/posts')
const json = await response.json()
setPosts(json)
}
load()
}, [])
return <pre>{JSON.stringify(posts, null, 2)}</pre>
}
getInitialProps - SSR works well
export default function Posts({posts}) {
return <pre>{JSON.stringify(posts, null, 2)}</pre>
}
Posts.getInitialProps = async () => {
const res = await fetch('http://localhost:3030/posts')
const json = await res.json()
return {posts: json}
}
using getServerSideProps instead of getInitialProps
export async function getServerSideProps({req}) {
const res = await fetch('http://localhost:3030/posts')
const json = await res.json()
return {
props: {posts: json}, // will be passed to the page component as props
}
}
npm i nextjs-progressbar --force
Configuring _app.js
import NextNprogress from 'nextjs-progressbar'
import '../styles/main.scss'
export default function MyApp({Component, pageProps}) {
return <>
<NextNprogress/>
<Component {...pageProps} />
</>
}
API by id: http://localhost:3000/api/echo/37
export default function echoById(req, res) {
res.json({
message: req.query.id
})
}
module.exports = {
env: {
API_URL: 'http://localhost:3030'
}
}
Now we can use global variable process.env.API_URL
Storing configuration in the environment separate from code
npm install dotenv
Dotenv loads environment variables from a .env file into process.env