Spaces:
Runtime error
Runtime error
git add backend/src/server.js git commit -m "Allow embedding in HF iframe: disable helmet frameguard + relax CSP" git push hf HEAD:main --force
aaef3a5
verified
| // backend/src/server.js | |
| import 'dotenv/config'; | |
| import express from 'express'; | |
| import cors from 'cors'; | |
| import helmet from 'helmet'; | |
| import morgan from 'morgan'; | |
| import mongoose from 'mongoose'; | |
| import path from 'node:path'; | |
| import { fileURLToPath } from 'node:url'; | |
| const __filename = fileURLToPath(import.meta.url); | |
| const __dirname = path.dirname(__filename); | |
| const MONGODB_URI = process.env.MONGODB_URI; | |
| const PORT = Number(process.env.PORT) || 7860; | |
| const app = express(); | |
| app.set('trust proxy', 1); | |
| // β Allow embedding in Hugging Face iframe | |
| app.use( | |
| helmet({ | |
| // HF embeds your app in an iframe; disable frameguard so it can load. | |
| frameguard: false, | |
| // Keep CSP off unless you author a custom policy that permits hf.co β hf.space. | |
| contentSecurityPolicy: false, | |
| // These can block some asset loads; relax for SPA builds. | |
| crossOriginEmbedderPolicy: false, | |
| crossOriginOpenerPolicy: { policy: 'same-origin-allow-popups' }, | |
| }) | |
| ); | |
| app.use( | |
| cors({ | |
| origin: true, // reflect request origin | |
| credentials: true, | |
| }) | |
| ); | |
| app.use(express.json({ limit: '1mb' })); | |
| app.use(morgan('tiny')); | |
| if (!MONGODB_URI) { | |
| console.error('β Missing MONGODB_URI environment variable.'); | |
| process.exit(1); | |
| } | |
| // Mongo | |
| mongoose.set('strictQuery', true); | |
| try { | |
| await mongoose.connect(MONGODB_URI); | |
| console.log('β MongoDB connected'); | |
| } catch (err) { | |
| console.error('β MongoDB connection error:', err.message || err); | |
| process.exit(1); | |
| } | |
| // Routes | |
| import productsRouter from './routes/products.routes.js'; | |
| app.get('/health', (_req, res) => { | |
| const conn = mongoose.connection.readyState === 1 ? 'connected' : 'disconnected'; | |
| res.json({ ok: conn === 'connected', db: conn }); | |
| }); | |
| app.use('/api/products', productsRouter); | |
| // Static frontend | |
| const clientDir = path.join(__dirname, '../../frontend/dist'); | |
| app.use(express.static(clientDir)); | |
| // SPA fallback (but not for /api/*) | |
| app.get('*', (req, res) => { | |
| if (req.path.startsWith('/api/')) return res.status(404).json({ error: 'Not found' }); | |
| res.sendFile(path.join(clientDir, 'index.html')); | |
| }); | |
| // Start | |
| app.listen(PORT, '0.0.0.0', () => { | |
| console.log(`π API running on http://0.0.0.0:${PORT}`); | |
| }); | |