Miscommunication between frontend and backend with vite/react app deployed to vercel

I have deployed an Spotify app I hva build in react with vite. But now it does not work.

So I have a vercel.json file in my root :

{ "builds": [ { "src": "api/server.js", "use": "@vercel/node" }, { "src": "client/package.json", "use": "@vercel/static-build", "config": { "distDir": "client/dist" } } ], "rewrites": [ { "source": "/api/(.*)", "destination": "/api/server.js" }, { "source": "/(.*)", "destination": "/client/index.html" } ] }

This is my server.js which is placed in /api/

import express from 'express';
import SpotifyWebApi from 'spotify-web-api-node';
import cors from 'cors';
import bodyParser from 'body-parser';

const app = express();
app.use(cors());
app.use(bodyParser.json());

// Create a SpotifyWebApi instance and configure it with your client credentials
const spotifyApi = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
redirectUri: process.env.SPOTIFY_REDIRECT_URI,
});

app.post('/api/refresh', (req, res) => {
const refreshToken = req.body.refreshToken;

spotifyApi.setRefreshToken(refreshToken); // Set the refresh token

spotifyApi.refreshAccessToken()
.then((data) => {
res.json({
accessToken: data.body.access_token,
expiresIn: data.body.expires_in,
});
})
.catch(err => {
console.log(err);
res.sendStatus(400);
});
});

app.post('/api/login', (req, res) => {
console.log('received login request with code:', code);
const code = req.body.code;

spotifyApi.authorizationCodeGrant(code)
.then(data => {
res.json({
accessToken: data.body.access_token,
refreshToken: data.body.refresh_token,
expiresIn: data.body.expires_in,
});
})
.catch((err) => {
console.log(err);
res.sendStatus(400);
});
});

app.get('/api/userSubscriptionLevel', async (req, res) => {
const token = req.headers.authorization.split(' ')[1];

spotifyApi.setAccessToken(token);

try {
const response = await spotifyApi.getMe();
const product = response.body.product;
res.json({ product });
} catch (error) {
console.error('Error fetching user subscription level:', error);
res.status(500).json({ error: 'Failed to fetch user subscription level' });
}
});

app.get('/api/search', async (req, res) => {
const { term, offset = 0, limit = 20 } = req.query;
const token = req.headers.authorization.split(' ')[1];

spotifyApi.setAccessToken(token);

try {
const response = await spotifyApi.searchTracks(term, { offset, limit });
res.json(response.body);
} catch (error) {
console.error('Error searching Spotify tracks:', error); // Log the detailed error
res.status(500).json({ error: error.message || 'Failed to search tracks' });
}
});

export default app;

My vite.config:

import react from '@vitejs/plugin-react';

export default defineConfig({
plugins: [react()],
build: {
outDir: 'dist',
assetsDir: 'src/assets',
},
define: {
"process.env": {},
},
server: {
port: 5173,
proxy: {
'/api': {
target: process.env.VITE_API_URL || 'http://localhost:3001',
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, ''),
},
},
},
});

Somehhow the callback from Spotify doesn’t work. But I doublechecked the enviromentals and they seem just fine. What do I miss?

Link to the app: https://walkify-alpha.vercel.app/

Hi, @marcobaass!

A few things to try:

1. Update the `vercel.json` file, especially the API rewrite rule.
{
  "builds": [
    { "src": "api/server.js", "use": "@vercel/node" },
    { "src": "client/package.json", "use": "@vercel/static-build", "config": { "distDir": "client/dist" } }
  ],
  "rewrites": [
    { "source": "/api/(.*)", "destination": "/api/server.js" },
    { "source": "/(.*)", "destination": "/client/index.html" }
  ]
}
  1. Verify environment variables in Vercel project settings (SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI).
  2. Ensure the Spotify Developer Dashboard redirect URI matches your Vercel deployment URL.
  3. Modify server.js to use CommonJS syntax instead of ES modules.
  4. Check the VITE_API_URL environment variable in Vercel project settings.
  5. Add more console.log statements in server.js for debugging.
  6. Review Vercel deployment logs for errors.
  7. Configure CORS settings correctly, specifying allowed origins.
  8. Verify client-side API request paths start with /api/.
  9. Consider splitting server.js into separate files for Vercel Functions if it’s too large.

Let us know how you get on!

  1. Update the vercel.json file, especially the API rewrite rule.

I updated the vercel.json like described, but now I get this error:

Error: No Output Directory named “build” found after the Build completed. You can configure the Output Directory in your Project Settings.

WARN! Due to builds existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: Error List

  1. Verify environment variables in Vercel project settings (SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI).

I checked them multible times.

  1. Ensure the Spotify Developer Dashboard redirect URI matches your Vercel deployment URL.

This is my redirect URI in the Spotify Dashboard:

  1. Modify server.js to use CommonJS syntax instead of ES modules.
    ?
  1. Check the VITE_API_URL environment variable in Vercel project settings.

It’s: https://walkify-alpha.vercel.app/api/

  1. Add more console.log statements in server.js for debugging.

The app does not even reach the server.js. So conole.logs there don’t matter yet.

  1. Review Vercel deployment logs for errors.

Where do I find these logs? When I navigate to the logs tab, there is nothing. Just a blank window saying “There are no runtime logs in this time range”

  1. Configure CORS settings correctly, specifying allowed origins.
    ?

  2. Verify client-side API request paths start with /api/.
    They do.

  3. Consider splitting server.js into separate files for Vercel Functions if it’s too large.
    ?

Thanks a lot.

Here are the build logs:

Running build in Washington, D.C., USA (East) – iad1

Cloning GitHub - marcobaass/walkify (Branch: main, Commit: 2c55b0c)

Cloning completed: 894.821ms

Restored build cache from previous deployment (5WKgq5sBpPDgi9gqtMrNddLtNJM6)

Running “vercel build”

Vercel CLI 37.4.0

WARN! Due to builds existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: Error List

Installing dependencies…

up to date in 3s

152 packages are looking for funding

run npm fund for details

Running “npm run build”

walkify-client@0.0.0 build

vite build

The CJS build of Vite’s Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.

vite v5.4.0 building for production…

transforming…

src/assets/imgs/walkman_blank_3_no_window.png referenced in src/assets/imgs/walkman_blank_3_no_window.png didn’t resolve at build time, it will remain unchanged to be resolved at runtime

src/assets/imgs/walkman_blank_3_no_window.png referenced in src/assets/imgs/walkman_blank_3_no_window.png didn’t resolve at build time, it will remain unchanged to be resolved at runtime
src/assets/imgs/tapeCase.png referenced in src/assets/imgs/tapeCase.png didn’t resolve at build time, it will remain unchanged to be resolved at runtime
✓ 110 modules transformed.
rendering chunks…
computing gzip size…
build/index.html 0.46 kB │ gzip: 0.29 kB
build/assets/monoton-v19-latin-regular-TKmQGCcv.woff2 16.52 kB
build/assets/gloria-hallelujah-v21-latin-regular-BuKjlT1h.woff2 18.60 kB
build/assets/gloria-hallelujah-v21-latin-regular-DgsbTjKx.ttf 33.27 kB
build/assets/monoton-v19-latin-regular-BzQSQFOf.ttf 39.72 kB
build/assets/walkman_blank_2-S_s2UYvr.png 296.94 kB
build/assets/index-DEBbFljA.css 16.58 kB │ gzip: 4.43 kB
build/assets/index-D66c0m5M.js 218.00 kB │ gzip: 73.05 kB
✓ built in 6.09s
Error: No Output Directory named “dist” found after the Build completed. You can configure the Output Directory in your Project Settings.
Learn More: Error List

Could you review your output directory in settings?

These are my settings. Thank you very much.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.