Next JS and Vercel - development vs production

Viewed 1051

I’ve built a basic movie DB app in Next JS to see how the framework works. It’s an app that allows you to perform CRUD operations to firebase, utilising the NextJS API endpoints.

I have the app working fine in development, however it does not work at all once to Vercel. I was wondering if anyone can shed some light?

Here is the first 'get all data' call upon initialisation. The other API calls follow the same pattern. None work once deployed.

My index page has this getInitialProps function…

Home.getInitialProps = async () => {
    const categories = await getCategories()
    const movies = await getMovies()
    const images = movies.map(movie => {
      return {
        id: `image-${movie.id}`,
        url: movie.cover,
        name: movie.name
      }
    })
    
    return {
      movies,
      images,
      categories
    }
  }

This fires off the getMovies function here…

export const getMovies = async () => {
    const res = await axios.get('http://localhost:3000/api/movies')
    return res.data

And the API endpoint it hits looks like this…

import firebase from '../../lib/firebase';

export default async(req, res) => {
    const moviesRef = firebase
            .collection('movies');
            const snapshot = await moviesRef.get();
            const movies = [];
            snapshot.forEach(doc => {
                movies.push({ id: doc.id, ...doc.data() })
            })
            res.json(movies)

Thanks in advance!

2 Answers

you should use your server link, not localhost.

You shouldn't hardcode http://localhost:3000 in the request's URL. You should omit it altogether since you're using Next.js API routes (same-origin).

export const getMovies = async () => {
    const res = await axios.get('/api/movies')
    return res.data
}

Edit: The above solution would work with API routes if the request was happening on the client-side only.

Since the request is made in getInitialProps, you should simply move the logic in your API route to a separate function (could very well be getMovies in this case) and call that directly in getInitialProps instead.

export const getMovies = async () => {
    const moviesRef = firebase.collection('movies');
    const snapshot = await moviesRef.get();
    const movies = [];
    snapshot.forEach(doc => {
        movies.push({ id: doc.id, ...doc.data() })
    });
    return movies;
}
Related