Page 1 of 5
Table of Contents
1. Set Up Your Next.js Backend
Option 1: Use Next.js API Routes (Serverless)
2. Connect Flutter to the Next.js API
Option 1: Using http package (Simple REST API)
3. Use Next.js as a WebSocket Backend (Optional)
Next.js WebSocket Server
Flutter WebSocket Client
4. Deploy Next.js Backend
Conclusion
how to use flutter with next js backend
To use Flutter with a Next.js backend, follow these steps:
1. Set Up Your Next.js Backend
Since Next.js is primarily a frontend framework, you need to create API routes to handle backend
logic. You can use either API Routes (built-in) or a separate Next.js server with a backend like Firebase,
Supabase, or a custom Node.js backend.
Option 1: Use Next.js API Routes (Serverless)
1. Inside your Next.js project, create an API route:
bash
mkdir -p pages/api
touch pages/api/hello.js
2. Add a simple API endpoint in pages/api/hello.js :
javascript
Page 2 of 5
export default function handler(req, res) {
res.status(200).json({ message: "Hello from Next.js API" });
}
3. Start your Next.js server:
bash
npm run dev
This will expose your API at http://localhost:3000/api/hello .
2. Connect Flutter to the Next.js API
Option 1: Using http package (Simple REST API)
1. Add http dependency in pubspec.yaml :
yaml
dependencies:
flutter:
sdk: flutter
http: ^0.13.5
2. Fetch data from the Next.js backend:
dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Future<String> fetchMessage() async {
final response = await http.get(Uri.parse('http://localhost:3000/api/hello'));
if (response.statusCode == 200) {
return jsonDecode(response.body)['message'];
} else {
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flutter & Next.js')),
body: Center(
child: FutureBuilder<String>(
future: fetchMessage(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
Page 3 of 5
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text(snapshot.data ?? 'No data');
}
},
),
),
),
);
}
}
3. Run the Flutter app:
bash
flutter run
3. Use Next.js as a WebSocket Backend (Optional)
If you needreal-time communication, consider using Next.js with WebSockets ( socket.io ).
Next.js WebSocket Server
1. Install dependencies:
bash
npm install socket.io
2. Create a WebSocket server in pages/api/socket.js :
javascript
import { Server } from "socket.io";
export default function handler(req, res) {
if (!res.socket.server.io) {
const io = new Server(res.socket.server);
res.socket.server.io = io;
io.on("connection", (socket) => {
console.log("Client connected");
socket.on("message", (msg) => {
io.emit("message", msg);
});
});
}
res.end();
}
Flutter WebSocket Client
1. Add web_socket_channel to pubspec.yaml :
Page 4 of 5
yaml
dependencies:
web_socket_channel: ^2.2.0
2. Connect Flutter to the WebSocket:
dart
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class WebSocketExample extends StatefulWidget {
@override
_WebSocketExampleState createState() => _WebSocketExampleState();
}
class _WebSocketExampleState extends State<WebSocketExample> {
final _channel = WebSocketChannel.connect(Uri.parse('ws://localhost:3000/api/socket'));
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('WebSocket Example')),
body: StreamBuilder(
stream: _channel.stream,
builder: (context, snapshot) {
return Center(
child: Text(snapshot.hasData ? '${snapshot.data}' : 'Waiting for data...'),
);
},
),
);
}
@override
void dispose() {
_channel.sink.close();
super.dispose();
}
}
3. Run both Next.js and Flutter, and they will communicate in real time.
4. Deploy Next.js Backend
Use Vercel (Recommended for API Routes)
Use Firebase, Supabase, or DigitalOcean for a custom backend
Use Express.js with Next.js if you need full control
Once deployed, update Flutter's API URLs to match your production backend.
Conclusion
Page 5 of 5
Use Next.js API Routes for serverless REST APIs.
Use WebSockets for real-time data transfer.
Deploy Next.js on Vercel or another cloud provider.
Consume APIs in Flutter using the http package or WebSockets.
Would you like to integrate authentication (Google, Firebase, JWT)? 🚀